private static Application.CreateContract.Handler GetCommandHandler() { var configurationBuilder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables(); var environment = Environment.GetEnvironmentVariable("NETCORE_ENVIRONMENT"); var isDevelopment = string.Equals(environment, "development", StringComparison.OrdinalIgnoreCase); if (isDevelopment) { configurationBuilder.AddUserSecrets(Assembly.GetCallingAssembly()); } var configuration = configurationBuilder.Build(); Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .Enrich.FromLogContext() .WriteTo.MSSqlServer(configuration.GetConnectionString("Logs"), "Logs", autoCreateSqlTable: true) .CreateLogger(); var loggerFactory = new LoggerFactory(); loggerFactory.AddSerilog(); var mediator = new OpenFaaSMediator(configuration, new Logger <OpenFaaSMediator>(loggerFactory)); var result = new Application.CreateContract.Handler(mediator); return(result); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime applicationLifetime) { // Disabilito il livelli di log di default dell'infrastruttura loggerFactory = new LoggerFactory(); // Serilog loggerFactory.AddSerilog(Log.Logger, false); applicationLifetime.ApplicationStopped.Register(Log.CloseAndFlush); // Configure JSNLog JsnlogConfiguration jsnlogConfiguration = new JsnlogConfiguration { corsAllowedOriginsRegex = ".*", serverSideMessageFormat = "Sent: %date, Browser: %userAgent, Message: %message" }; app.UseJSNLog(new LoggingAdapter(loggerFactory), jsnlogConfiguration); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
protected ILogger <T> CreateLogger <T>() { var logger = new LoggerFactory(); logger.AddSerilog(); return(logger.CreateLogger <T>()); }
public static void ConfigureLogger(LogOptions options, IEnumerable <LogMessage> initialLogMessages = null) { LoggerFactory.AddSerilog(new LoggerConfiguration().MinimumLevel.Is(options.LogLevel).Enrich.FromLogContext().WriteTo.Console().CreateLogger()); if (options.LogToFile) { // log on the lowest level to the log file var logFilesPath = Path.Combine(options.OutputPath, "logs"); LoggerFactory.AddFile(logFilesPath + "/log-{Date}.txt", MSLogLevel.Trace); } if (initialLogMessages != null) { var logger = LoggerFactory.CreateLogger("InitialLogging"); foreach (var logMessage in initialLogMessages) { logger.Log(logMessage.LogLevel, logMessage.EventId, logMessage.State, logMessage.Exception, logMessage.Formatter); } } // When stryker log level is debug or trace, set LibGit2Sharp loglevel to info if (options.LogLevel < LogEventLevel.Information) { var libGit2SharpLogger = LoggerFactory.CreateLogger(nameof(LibGit2Sharp)); GlobalSettings.LogConfiguration = new LogConfiguration(LibGitLogLevel.Info, (level, message) => libGit2SharpLogger.Log(LogLevelMap[level], message)); } }
/// <summary> /// Sets the logger. /// </summary> /// <param name="options">The BindOpen host options to consider.</param> /// <param name="initBuilder">The logger builder action to consider.</param> /// <returns></returns> public static ITBdoHostOptions <S> SetLogger <S>( this ITBdoHostOptions <S> options, Func <LoggerConfiguration, LoggerConfiguration> initLoggerConfig, bool isTraceLoggerAtStartup = false) where S : class, IBdoAppSettings, new() { options.SetLogger(h => { var config = new LoggerConfiguration(); initLoggerConfig?.Invoke(config); var loggerFactory = new LoggerFactory(); loggerFactory.AddSerilog(config.CreateLogger()); return(loggerFactory.CreateLogger <IBdoHost>()); }); if (isTraceLoggerAtStartup) { var config = new LoggerConfiguration(); config.WriteTo.Trace(); var loggerFactory = new LoggerFactory(); loggerFactory.AddSerilog(config.CreateLogger()); options.SetLoggerAtStartup(loggerFactory); } return(options); }
public LoggerServiceRegistry() { LoggingLevel.MinimumLevel = Serilog.Events.LogEventLevel.Information; if (!Environment.UserInteractive) { Log.Logger = Log.Logger = new LoggerConfiguration() .MinimumLevel.ControlledBy(LoggingLevel) .WriteTo.File( path: Path.Combine(dirLocation, $@"L1_alert.trc"), outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] [{SourceContext}] {Message:lj}{NewLine}{Exception}", rollOnFileSizeLimit: true ) .CreateLogger(); } else { Log.Logger = Log.Logger = new LoggerConfiguration() .MinimumLevel.ControlledBy(LoggingLevel) .WriteTo.Console(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] [{SourceContext}] {Message:lj}{NewLine}{Exception}") .WriteTo.File( path: Path.Combine(dirLocation, $@"L1_alert.trc"), outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] [{SourceContext}] {Message:lj}{NewLine}{Exception}", rollOnFileSizeLimit: true ) .CreateLogger(); } loggerFactory.AddSerilog(); For <ILoggerFactory>().Use(loggerFactory).Singleton(); For(typeof(Microsoft.Extensions.Logging.ILogger <>)).Use(typeof(LoggerWrapper <>)); }
public ConsoleOneLineLoggerFactory() { _factory = new LoggerFactory(); _factory.AddSerilog(new LoggerConfiguration() .WriteTo.Console(outputTemplate: "{Message:lj}{NewLine}") .CreateLogger()); }
static void Main(string[] args) { var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json") .Build(); Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(configuration) .CreateLogger(); LoggerFactory loggerFactory = new LoggerFactory(); loggerFactory.AddSerilog(); var logger = loggerFactory.CreateLogger <Program>(); for (int i = 0; i < 10; i++) { logger.LogInformation($"Message {i}"); } Console.WriteLine($"Finish to log messages."); Console.Read(); Log.CloseAndFlush(); }
public static void Run() { var scopes = new BlockingCollection <(IDisposable, TaskCompletionSource <int>)>(); new Thread(_ => { while (true) { var(scope, tcs) = scopes.Take(); scope.Dispose(); tcs.TrySetResult(0); } }).Start(); var loggerFactory = new LoggerFactory(); loggerFactory.AddSerilog(); var logger = loggerFactory.CreateLogger("category"); var tasks = new List <Task>(); for (var i = 0; i < 100; i++) { var scope = logger.BeginScope("scope name"); var tcs = new TaskCompletionSource <int>(); logger.LogInformation("begin context"); scopes.Add((scope, tcs)); tasks.Add(tcs.Task); } Task.WaitAll(tasks.ToArray()); }
private static void InitServices() { ILoggerFactory loggerFactory = new LoggerFactory(); loggerFactory.AddSerilog(); Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Console() .WriteTo.File( $@"../../../dps.logs", fileSizeLimitBytes: 1_000_000, rollOnFileSizeLimit: true, shared: true) .CreateLogger(); _sp = new ServiceCollection() .AddCertificateManager() .AddSingleton <IConfiguration>(GetConfig()) .AddTransient <DpsRegisterDevice>() .AddTransient <DpsEnrollmentGroup>() .AddTransient <DpsIndividualEnrollment>() .AddTransient <IoTHubUpdateDevice>() .AddTransient <DpsUpdateDevice>() .AddSingleton(loggerFactory) .BuildServiceProvider(); }
public static void ConfigureLogger(LogOptions options, IEnumerable <LogMessage> initialLogMessages = null) { LoggerFactory.AddSerilog(new LoggerConfiguration() .MinimumLevel.Is(options.LogLevel) .Enrich.FromLogContext() .WriteTo.Console() .CreateLogger()); if (options.LogToFile) { // log on the lowest level to the log file var logFilesPath = Path.Combine(options.OutputPath, "logs"); LoggerFactory.AddFile(logFilesPath + "/log-{Date}.txt", LogLevel.Trace); } if (initialLogMessages != null) { var logger = LoggerFactory.CreateLogger("InitialLogging"); foreach (var logMessage in initialLogMessages) { logger.Log(logMessage.LogLevel, logMessage.EventId, logMessage.State, logMessage.Exception, logMessage.Formatter); } } }
static void Main(string[] args) { // Set up logging ILoggerFactory loggerFactory = new LoggerFactory(); // MS console loggerFactory.AddConsole(LogLevel.Trace); // Trace=Most detailed on Microsoft.Extensions.Logging // Serilog console var configuration = new LoggerConfiguration() .MinimumLevel.Verbose() // Verbose=Most detailed on Serilog .Enrich.WithProperty("servername", Environment.MachineName) .WriteTo.ColoredConsole(outputTemplate: "SERILOG: [{Level}]: {Message}{NewLine}"); // Specific template, to make it stand out on the console loggerFactory.AddSerilog(configuration.CreateLogger()); // Log on all levels var logger = loggerFactory.CreateLogger <Program>(); logger.LogCritical("**critical**"); logger.LogDebug("**debug**"); // Not logged by Serilog! logger.LogError("**error**"); logger.LogInformation("**info**"); logger.LogTrace("**trace**"); // Not logged by Serilog! logger.LogWarning("**warning**"); Console.ReadKey(); }
public ILoggerFactory CreateLoggerFactory(string aiKey) { var configuration = new TelemetryConfiguration { InstrumentationKey = aiKey }; configuration.TelemetryInitializers.Add(new OperationContextTelemetryInitializer(() => RemotingContext.GetData(HeaderIdentifiers.TraceId)?.ToString())); new LiveStreamProvider(configuration).Enable(); var loggerFactory = new LoggerFactory(); var logger = new LoggerConfiguration() .Enrich.FromLogContext() .WriteTo .ApplicationInsights( configuration, (logEvent, formatter) => new TelemetryBuilder(_context, logEvent).LogEventToTelemetryConverter()) .CreateLogger(); InitContextProperties(); loggerFactory.AddSerilog(logger, true); return(loggerFactory); }
public static async Task <LanguageServerHost> Create( Stream input, Stream output, string logFilePath, LogLevel minLogLevel) { var exportProvider = CreateHostServices(); var logger = new LoggerConfiguration() .Enrich.FromLogContext() .WriteTo.File(logFilePath) .CreateLogger(); var loggerFactory = new LoggerFactory( ImmutableArray <ILoggerProvider> .Empty, new LoggerFilterOptions { MinLevel = minLogLevel }); loggerFactory.AddSerilog(logger); var result = new LanguageServerHost(exportProvider, logger, loggerFactory); await result.InitializeAsync(input, output); return(result); }
static void Main(string[] args) { var brokers = args[0]; var topic = args[1]; Log.Logger = new LoggerConfiguration() .WriteTo.Kafka(batchSizeLimit: 50, period: 1, brokers: brokers, topic: topic) .CreateLogger(); LoggerFactory loggerFactory = new LoggerFactory(); loggerFactory .AddSerilog(); var logger = loggerFactory.CreateLogger <Program>(); for (int i = 0; i < 10; i++) { logger.LogInformation($"Message {i}"); } Console.WriteLine($"Finish to log messages."); Console.Read(); Log.CloseAndFlush(); }
public static void ConfigureLogger(LogOptions options, IEnumerable <LogMessage> initialLogMessages = null) { LoggerFactory.AddSerilog(new LoggerConfiguration() .MinimumLevel.Is(options.LogLevel) .Enrich.FromLogContext() .WriteTo.Console() .CreateLogger()); if (options.LogToFile) { // log on the lowest level to the log file var logFilesPath = Path.Combine(options.OutputPath, "logs"); LoggerFactory.AddFile(logFilesPath + "/log-{Date}.txt", LogLevel.Trace); } if (initialLogMessages != null) { var logger = LoggerFactory.CreateLogger("InitialLogging"); foreach (var logMessage in initialLogMessages) { // Create the generic variant of the method to make sure any consumer can use typeof(TState) _logMethodInfo.MakeGenericMethod(logMessage.StateType) .Invoke( logger, new[] { logMessage.LogLevel, logMessage.EventId, logMessage.State, logMessage.Exception, logMessage.Formatter }); } } }
protected override IWebHostBuilder CreateWebHostBuilder() { return(base.CreateWebHostBuilder().ConfigureServices(services => { services.AddMvc() .AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore) .SetCompatibilityVersion(CompatibilityVersion.Version_2_2); //the only option needed since the mongo client is instanciated in the test services.Configure <MongoDBConfiguration>(x => { x.DatabaseName = "TestMachine"; x.EventCollection = "TestEvents"; }); //this services are the same but the mongo client is inject in the test constructor services.AddScoped <IMongo, MongoService>(); services.AddScoped <IStoreData, StoreDataService>(); services.AddScoped <IGetData, GetDataService>(); //configure the fake background services services.AddScoped <IWebSocket, WebSocketServiceFake>(); services.AddHostedService <WebSocketHostingServiceFake>(); }) .Configure(app => { var loggingFactory = new LoggerFactory(); //add serilog to logging pipeline loggingFactory.AddSerilog(); //register the base routing of the application app.UseMvc(routes => { routes.MapRoute( name: "default", template: "v1/{controller=Home}/{action=Index}/{id?}"); }); })); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); // config serilog var logger = new LoggerConfiguration() .MinimumLevel.Information() .WriteTo.MySink(new SinkConfiguration { ClientName = "Sample Console App", RabbitMqHostName = "127.0.0.1", RabbitMqPort = 15672, RabbitMqUsername = "******", RabbitMqPassword = "******", RabbitMqExchangeName = "MicroLogger-ExchangeName", RabbitMqExchangeType = MicroLib.RabbitMQ.Client.Helper.Standard.Model.ExchangeType.Direct, RabbitMqRouteKey = "MicroLogger-RoutKeyName", RabbitMqQueueName = "MicroLogger-QueueName" }) .CreateLogger(); var loggerFactory = new LoggerFactory(); loggerFactory.AddSerilog(logger); services.AddSingleton <ILoggerFactory>(loggerFactory); }
/// <summary> /// Creates the LoggerFactory implementing ILoggerfactory of Microsoft.Extensions.Loggins /// </summary> /// <returns></returns> private static ILoggerFactory CreateLoggerFactory(Serilog.ILogger logger) { ILoggerFactory loggerFactory = new LoggerFactory(); loggerFactory.AddSerilog(logger); return(loggerFactory); }
public static ILoggerFactory CreateLoggerFactory( LoggerConfiguration loggerConfiguration = null, LogEventLevel applicationInsightsMinimumLogEventLevel = LogEventLevel.Information, TelemetryConfiguration telemetryConfiguration = null) { // setup Serilog if (loggerConfiguration == null) { loggerConfiguration = CreateDefaultLoggerConfiguration(); } if (telemetryConfiguration != null && !string.IsNullOrEmpty(telemetryConfiguration.InstrumentationKey)) { loggerConfiguration = loggerConfiguration.WriteTo.ApplicationInsights( telemetryConfiguration, TelemetryConverter.Traces, applicationInsightsMinimumLogEventLevel); } Log.Logger = loggerConfiguration.CreateLogger(); // hook-up Serilog to Microsoft.Extensions.Logging var loggerFactory = new LoggerFactory(); loggerFactory.AddSerilog(); if (!Trace.Listeners.OfType <SerilogTraceListener.SerilogTraceListener>().Any()) { // hook into anything that is being traced in other libs using system.diagnostics.trace Trace.Listeners.Add(new SerilogTraceListener.SerilogTraceListener()); } return(loggerFactory); }
private static void ConfigureSerilog(IServiceCollection services) { var serilogConfiguration = _configuration.GetSection("Serilog"); var rabbitConfig = new RabbitMQClientConfiguration { Username = serilogConfiguration["RabbitMqUser"], Password = serilogConfiguration["RabbitMqPassword"], Exchange = "", RouteKey = serilogConfiguration["RabbitMqRoutingKey"], Port = Convert.ToInt32(serilogConfiguration["RabbitMqPort"]), DeliveryMode = RabbitMQDeliveryMode.Durable, }; rabbitConfig.Hostnames.Add(serilogConfiguration["RabbitMqHost"]); Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .MinimumLevel.Information() .MinimumLevel.Override("Microsoft", new LoggingLevelSwitch(LogEventLevel.Error)) .Enrich.FromLogContext() //.WriteTo.Console() If you want to view the log on the console .WriteTo.RabbitMQ((clientConfiguration, sinkConfiguration) => { clientConfiguration.From(rabbitConfig); sinkConfiguration.TextFormatter = new JsonFormatter(); }) .CreateLogger(); var loggerFactory = new LoggerFactory(); loggerFactory.AddSerilog(); services.AddSingleton <ILoggerFactory>(loggerFactory); }
private static void ConfigureServices(ServiceCollection services) { ILoggerFactory loggerFactory = new LoggerFactory(); services.AddSingleton(loggerFactory); ApplicationLogging.LoggerFactory = loggerFactory; var configuration = GetConfiguration(); services.AddSingleton <IConfigurationRoot>(configuration); services.AddLogging(loggingBuilder => { loggingBuilder.AddConfiguration(configuration.GetSection("Logging")); }); #if USE_SERILOG var logger = new LoggerConfiguration() .ReadFrom.Configuration(configuration) .CreateLogger(); loggerFactory.AddSerilog(logger); #endif services.AddTransient <Application>(); services.AddTransient <Calculator>(); }
public ILoggerFactory LoggerFactoryConfiguration() { var log = new SerilogDI(LoadConfiguration()).ConfigurationSerilog().CreateLogger(); var fac = new LoggerFactory(); fac.AddSerilog(log); return(fac); }
public LoggerBuilder AddSerilogLogger(Serilog.ILogger logger) { LoggerFactory loggerFactory = new LoggerFactory(); loggerFactory.AddSerilog(logger); _logger = loggerFactory.CreateLogger("Logger"); return(this); }
/// <summary> /// Creates the LoggerFactory implementing ILoggerfactory of Microsoft.Extensions.Loggins /// </summary> /// <returns></returns> private static ILoggerFactory CreateLoggerFactory(LoggerConfiguration loggerConfiguration) { ILoggerFactory loggerFactory = new LoggerFactory(); var logger = loggerConfiguration.CreateLogger(); loggerFactory.AddSerilog(logger); return(loggerFactory); }
static MicrosoftLoggingFactory() { if (LoggerFactory == null) { var loggerFactory = new LoggerFactory(); loggerFactory.AddSerilog(SerilogFactory.Instance); LoggerFactory = loggerFactory; } }
static FileLogging() { var date = System.DateTime.Today; _fileName = Assembly.GetExecutingAssembly().GetName().Name; PhysicalPath = Path.Combine($"logs", _fileName); Factory.AddSerilog(); Factory.AddFile(PhysicalPath); }
/// <summary> /// This is the entry point of the service host process. /// </summary> private static void Main() { try { // This line registers an Actor Service to host your actor class with the Service Fabric runtime. // The contents of your ServiceManifest.xml and ApplicationManifest.xml files // are automatically populated when you build this project. // For more information, see https://aka.ms/servicefabricactorsplatform var log = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Trace() .CreateLogger(); using (var container = new FabricContainer()) { var loggerfac = new LoggerFactory() as ILoggerFactory; loggerfac.AddSerilog(); container.RegisterInstance(loggerfac); container.RegisterType <IMyScopedDependency, MyScopedDependency>(new HierarchicalLifetimeManager()); container.WithActor <MyTestActor>(new ActorServiceSettings() { ActorGarbageCollectionSettings = new ActorGarbageCollectionSettings(120, 60) }); container.WithActor <MySecondTestActor>(new ActorServiceSettings() { ActorGarbageCollectionSettings = new ActorGarbageCollectionSettings(30, 10) }); container.WithActor <DependencyInjectionActorSample>(new ActorServiceSettings() { ActorGarbageCollectionSettings = new ActorGarbageCollectionSettings(300, 100) }); Task.Delay(15000).ContinueWith(async(task) => { var node = FabricRuntime.GetNodeContext(); var instanceId = node.NodeInstanceId; if (node.NodeType == "NodeType3") { await ActorProxy.Create <IMyTestActor>(new ActorId("MyCoolActor")).StartAsync(); } }).Wait(); Thread.Sleep(Timeout.Infinite); } } catch (Exception e) { ActorEventSource.Current.ActorHostInitializationFailed(e.ToString()); throw; } }
public static ContainerBuilder UseSerilog(this ContainerBuilder builder, Action <LoggerSinkConfiguration> action) { ILoggerFactory loggerFactory = new LoggerFactory(); var loggerInstance = loggerFactory.CreateLogger(Constants.SOLUTION_ENTRYPOINT_NAME); loggerFactory.AddSerilog(CreateLogger(action)); builder.RegisterInstance(loggerInstance).As <ILogger>(); return(builder); }
public Task Run() { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("ADD CREDIT TO TEXT FILES\n"); Console.ResetColor(); Console.WriteLine( $"Text dir: {_txtDir}\n" + $"Resp value: {_respValue}\n" + $"PersName value: {_persValue}\n" + $"Dry run: {_dry}\n"); ILoggerFactory loggerFactory = new LoggerFactory(); loggerFactory.AddSerilog(Log.Logger); Log.Logger.Information("ADD CREDIT TO TEXT FILES"); foreach (string filePath in FileEnumerator.Enumerate(_txtDir, @"^[^-]+-[^-]+\.xml", true, true)) { Console.WriteLine(filePath); Log.Logger.Information(filePath); XDocument doc = XDocument.Load(filePath, LoadOptions.PreserveWhitespace); // TEI/teiHeader/fileDesc/seriesStmt/ XElement series = doc.Root ?.Element(XmlHelper.TEI + "teiHeader") ?.Element(XmlHelper.TEI + "fileDesc") ?.Element(XmlHelper.TEI + "seriesStmt"); if (series == null) { Log.Logger?.Error( $"Unable to find seriesStmt in header for {Path.GetFileName(filePath)}"); continue; } // <respStmt> // <resp key="MQDQ">RESPVALUE</resp> // <persName>PERSVALUE</persName> // </respStmt> series.Add(new XElement(XmlHelper.TEI + "respStmt", new XElement(XmlHelper.TEI + "resp", new XAttribute("key", "MQDQ"), _respValue), new XElement(XmlHelper.TEI + "persName", _persValue))); if (!_dry) { doc.Save(filePath); } } return(Task.CompletedTask); }