public Startup(IConfiguration configuration) { Configuration = configuration; // Configuring Serilog. TODO -> Find better place for this than a constructor. var serilogOptions = new SerilogOptions(); Configuration.Bind("SerilogOptions", serilogOptions); var networkCredential = new NetworkCredential( serilogOptions.FromEmail, serilogOptions.FromEmailPassword); var emailConnectionInfo = new EmailConnectionInfo { Port = serilogOptions.Port, FromEmail = serilogOptions.FromEmail, ToEmail = serilogOptions.ToEmail, EnableSsl = serilogOptions.EnableSsl, EmailSubject = serilogOptions.EmailSubject, MailServer = serilogOptions.SmtpServer, NetworkCredentials = networkCredential }; Log.Logger = new LoggerConfiguration() .MinimumLevel.Information() .WriteTo.Console() .WriteTo.Email(emailConnectionInfo, restrictedToMinimumLevel: LogEventLevel.Error) .CreateLogger(); }
public void SerilogOptions_Set_Correctly() { // arrange var appSettings = new Dictionary <string, string> { { "Serilog:MinimumLevel:Default", "Error" }, { "Serilog:MinimumLevel:Override:Microsoft", "Warning" }, { "Serilog:MinimumLevel:Override:Steeltoe.Extensions", "Verbose" }, { "Serilog:MinimumLevel:Override:Steeltoe", "Information" }, { "Serilog:SubloggerConfigKeyExclusions:0", "Enrichers" }, { "Serilog:SubloggerConfigKeyExclusions:1", "WriteTo" }, { "Serilog:SubloggerConfigKeyExclusions:2", "MinimumLevel" }, }; var builder = new ConfigurationBuilder().AddInMemoryCollection(appSettings); // act var serilogOptions = new SerilogOptions(builder.Build()); // assert Assert.Equal(LogEventLevel.Error, serilogOptions.MinimumLevel.Default); Assert.Equal(LogEventLevel.Warning, serilogOptions.MinimumLevel.Override["Microsoft"]); Assert.Equal(LogEventLevel.Information, serilogOptions.MinimumLevel.Override["Steeltoe"]); Assert.Equal(LogEventLevel.Verbose, serilogOptions.MinimumLevel.Override["Steeltoe.Extensions"]); Assert.Collection <string>( serilogOptions.SubloggerConfigKeyExclusions, x => Assert.Contains("Enrichers", x), x => Assert.Contains("WriteTo", x), x => Assert.Contains("MinimumLevel", x)); }
private IOptionsMonitor <SerilogOptions> GetConfigurationFromFile() { var builder = new ConfigurationBuilder() .AddJsonFile("serilogSettings.json"); var configuration = builder.Build(); var serilogOptions = new SerilogOptions(); serilogOptions.SetSerilogOptions(configuration); return(new TestOptionsMonitor <SerilogOptions>(serilogOptions)); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); var serilogOptions = new SerilogOptions(); Configuration.GetSection("serilog").Bind(serilogOptions); services.AddSingleton <SerilogOptions>(serilogOptions); ConfigureRabbitMq(services, Configuration.GetSection("rabbitmq")); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. var serilogOptions = new SerilogOptions(); Configuration.GetSection("serilog").Bind(serilogOptions); services.AddSingleton <SerilogOptions>(serilogOptions); services.AddLogging(); services.AddControllers(); ConfigureRabbitMq(services); }
public void SerilogOptions_NoError_When_NotConfigured() { var appSettings = new Dictionary <string, string>(); var builder = new ConfigurationBuilder().AddInMemoryCollection(appSettings); var serilogOptions = new SerilogOptions(); serilogOptions.SetSerilogOptions(builder.Build()); Assert.Equal(LogEventLevel.Information, serilogOptions.MinimumLevel.Default); Assert.NotNull(serilogOptions.GetSerilogConfiguration()); }
public void SerilogOptions_NoError_When_NotConfigured() { // arrange var appSettings = new Dictionary <string, string>(); var builder = new ConfigurationBuilder().AddInMemoryCollection(appSettings); // act var serilogOptions = new SerilogOptions(builder.Build()); // assert Assert.Equal(LogEventLevel.Verbose, serilogOptions.MinimumLevel.Default); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. var serilogOptions = new SerilogOptions(); Configuration.GetSection("serilog").Bind(serilogOptions); services.AddSingleton <SerilogOptions>(serilogOptions); services.AddLogging(); services.AddMvc(); services.AddSingleton <IRepository>(_ => new InMemoryRepository()); ConfigureRabbitMq(services); //services.Configure<RabbitMqOptions>(Configuration.GetSection("rabbitmq")); }
public void SerilogOptions_Set_Correctly_When_MinimumLevel_Is_String() { var appSettings = new Dictionary <string, string> { { "Serilog:MinimumLevel", "Error" } }; var builder = new ConfigurationBuilder().AddInMemoryCollection(appSettings); var serilogOptions = new SerilogOptions(); serilogOptions.SetSerilogOptions(builder.Build()); Assert.Equal(LogEventLevel.Error, serilogOptions.MinimumLevel.Default); Assert.NotNull(serilogOptions.GetSerilogConfiguration()); }
public void SerilogOptions_NoError_When_NotConfigured() { // arrange var appSettings = new Dictionary <string, string>(); var builder = new ConfigurationBuilder().AddInMemoryCollection(appSettings); // act var serilogOptions = new SerilogOptions(builder.Build()); // assert Assert.Equal(LogEventLevel.Verbose, serilogOptions.MinimumLevel.Default); Assert.Collection <string>( serilogOptions.SubloggerConfigKeyExclusions, x => Assert.Contains("WriteTo", x), x => Assert.Contains("MinimumLevel", x)); }
public void SerilogOptions_Set_Correctly_Via_LoggerConfiguration() { var loggerConfiguration = new Serilog.LoggerConfiguration() .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .MinimumLevel.Override("Steeltoe.Extensions", LogEventLevel.Verbose) .MinimumLevel.Override("Steeltoe", LogEventLevel.Information); var serilogOptions = new SerilogOptions(); serilogOptions.SetSerilogOptions(loggerConfiguration); Assert.Equal(LogEventLevel.Debug, serilogOptions.MinimumLevel.Default); Assert.Equal(LogEventLevel.Warning, serilogOptions.MinimumLevel.Override["Microsoft"]); Assert.Equal(LogEventLevel.Verbose, serilogOptions.MinimumLevel.Override["Steeltoe.Extensions"]); Assert.NotNull(serilogOptions.GetSerilogConfiguration()); }
private IOptionsMonitor <SerilogOptions> GetConfiguration() { var appSettings = new Dictionary <string, string> { { "Serilog:MinimumLevel:Default", "Information" }, { "Serilog:MinimumLevel:Override:Microsoft", "Warning" }, { "Serilog:MinimumLevel:Override:Steeltoe.Extensions", "Verbose" }, { "Serilog:MinimumLevel:Override:Steeltoe", "Information" }, { "Serilog:MinimumLevel:Override:A", "Information" }, { "Serilog:MinimumLevel:Override:A.B.C", "Information" }, { "Serilog:WriteTo:Name", "Console" }, }; var builder = new ConfigurationBuilder().AddInMemoryCollection(appSettings); var configuration = builder.Build(); var serilogOptions = new SerilogOptions(); serilogOptions.SetSerilogOptions(configuration); return(new TestOptionsMonitor <SerilogOptions>(serilogOptions)); }
public void SerilogOptions_Set_Correctly() { var appSettings = new Dictionary <string, string> { { "Serilog:MinimumLevel:Default", "Error" }, { "Serilog:MinimumLevel:Override:Microsoft", "Warning" }, { "Serilog:MinimumLevel:Override:Steeltoe.Extensions", "Verbose" }, { "Serilog:MinimumLevel:Override:Steeltoe", "Information" }, }; var builder = new ConfigurationBuilder().AddInMemoryCollection(appSettings); var serilogOptions = new SerilogOptions(); serilogOptions.SetSerilogOptions(builder.Build()); Assert.Equal(LogEventLevel.Error, serilogOptions.MinimumLevel.Default); Assert.Equal(LogEventLevel.Warning, serilogOptions.MinimumLevel.Override["Microsoft"]); Assert.Equal(LogEventLevel.Information, serilogOptions.MinimumLevel.Override["Steeltoe"]); Assert.Equal(LogEventLevel.Verbose, serilogOptions.MinimumLevel.Override["Steeltoe.Extensions"]); Assert.NotNull(serilogOptions.GetSerilogConfiguration()); }
private static void Configure(SerilogOptions options, LoggerConfiguration config, LoggerConfigurationOptions configurationOptions, WebHostBuilderContext ctx) { if (configurationOptions.UseEnvironmentVariables) { options.ServiceName = TryGetEnvironmentVariable("SERVICE_POD_NAME"); options.FilePath = TryGetEnvironmentVariable("SERILOG_LOG_PATH"); } else { ValidateOptions(new[] { options?.FilePath, options?.ServiceName }); } config .MinimumLevel.Override("Microsoft.AspNetCore", configurationOptions.OverrideDefaultLevelLog) .MinimumLevel.Is(configurationOptions.MinimumLevelLog) .Enrich.WithProperty("ServiceId", options.ServiceName) .Enrich.WithProperty("Environment", ctx.HostingEnvironment.EnvironmentName) .Enrich.FromLogContext() .WriteTo.Console(); if (!configurationOptions.WriteToFile) { return; } var fileLogName = $"{options.ServiceName}_.log"; config.WriteTo.File( new JsonFormatter(renderMessage: false), Path.Combine(options.FilePath, fileLogName), rollingInterval: RollingInterval.Day, rollOnFileSizeLimit: true, retainedFileCountLimit: 5, fileSizeLimitBytes: 500_000_000, shared: true, flushToDiskInterval: TimeSpan.FromSeconds(1) ); }
private static ILoggingBuilder AddSerilog( ILoggingBuilder builder, IConfiguration configuration, SerilogOptions options) { if (options == default) { throw new ArgumentNullException(nameof(options)); } var config = new LoggerConfiguration(); config.ReadFrom.Configuration(configuration, nameof(SerilogOptions)); if (options.ElasticsearchOptions != default) { config.WriteTo.Elasticsearch(options.ElasticsearchOptions.SinkOptions); } var logger = config.CreateLogger(); builder.AddSerilog(logger, options.Dispose); return(builder); }
public static IWebHost BuildWebHost(string[] args) { var builder = new WebHostBuilder() .UseKestrel(x => { x.AddServerHeader = false; }) .UseUrls("Http://*:5000") .UseContentRoot(Directory.GetCurrentDirectory()) .ConfigureAppConfiguration((hostingContext, config) => { var env = hostingContext.HostingEnvironment; config.SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); if (env.IsDevelopment()) { var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName)); if (appAssembly != null) { config.AddUserSecrets(appAssembly, optional: true); } } config.AddEnvironmentVariables(); if (args != null) { config.AddCommandLine(args); } }) .ConfigureLogging((hostingContext, logging) => { logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); var options = hostingContext.Configuration.GetSection("Serilog").Get <SerilogOptions>(); if (options == null) { options = new SerilogOptions { StdOut = true, LogMinLevel = LogEventLevel.Debug, SourceContextFilterOptions = new SourceContextFilterOptions { MinLevel = LogEventLevel.Warning, Rules = new[] { new SourceContextFilterRule { LogLevel = LogEventLevel.Warning, SourceContextName = "Microsoft" } } } }; } Log.Logger = LogBuilder.Create(options); Log.Information("Getting the motors running..."); logging.AddSerilog(logger: Log.Logger, dispose: true); }) .UseIISIntegration() .UseDefaultServiceProvider((context, options) => { options.ValidateScopes = context.HostingEnvironment.IsDevelopment(); }) .UseStartup <Startup>(); return(builder.Build()); }
/// <summary> /// Initializes a new instance of the <see cref="ConfigureLogging" /> class. /// </summary> /// <param name="environment">The hosting environment.</param> /// <param name="options">The Serilog config from app.settings.</param> /// <param name="logEnricher">The log enricher.</param> public ConfigureLogging(IHostingEnvironment environment, IOptions <SerilogOptions> options, ILogEventEnricher logEnricher) { this.environment = environment; this.options = options.Value; this.logEnricher = logEnricher; }
public static AppBuilder AddConsoleSerilogLogging(this AppBuilder instance, bool includeDistributedTracing = false, bool addDebug = false) { LoggingConstants.IncludeDistributedTracing = includeDistributedTracing; var inMemoryConfigStore = ReflectionHelper .GetNonPublicInstancePropertyValue <Dictionary <string, string> >(instance, "InMemoryConfigStore"); inMemoryConfigStore["Serilog:MinimumLevel:Default"] = "Information"; inMemoryConfigStore["Serilog:MinimumLevel:Override:Microsoft"] = "Warning"; inMemoryConfigStore["Serilog:MinimumLevel:Override:System"] = "Warning"; inMemoryConfigStore["Serilog:MinimumLevel:Override:PivotalServices"] = "Warning"; inMemoryConfigStore["Serilog:MinimumLevel:Override:Steeltoe"] = "Warning"; inMemoryConfigStore["Serilog:Using:0"] = "Serilog.Sinks.Console"; inMemoryConfigStore["Serilog:Using:1"] = "Serilog.Sinks.Debug"; inMemoryConfigStore["Serilog:WriteTo:0:Name"] = "Console"; inMemoryConfigStore["Serilog:WriteTo:1:Name"] = "Debug"; if (includeDistributedTracing) { inMemoryConfigStore["Serilog:WriteTo:0:Args:outputTemplate"] = "[{Level}]{CorrelationContext}=> RequestPath:{RequestPath} => {SourceContext} => {Message} {Exception}{NewLine}"; inMemoryConfigStore["Serilog:WriteTo:1:Args:outputTemplate"] = "[{Level}]{CorrelationContext}=> RequestPath:{RequestPath} => {SourceContext} => {Message} {Exception}{NewLine}"; inMemoryConfigStore["management:tracing:AlwaysSample"] = "true"; inMemoryConfigStore["management:tracing:UseShortTraceIds"] = "false"; inMemoryConfigStore["management:tracing:EgressIgnorePattern"] = "/api/v2/spans|/v2/apps/.*/permissions|/eureka/.*|/oauth/.*"; } else { inMemoryConfigStore["Serilog:WriteTo:0:Args:outputTemplate"] = "[{Level}]RequestPath:{RequestPath} => {SourceContext} => {Message} {Exception}{NewLine}"; inMemoryConfigStore["Serilog:WriteTo:1:Args:outputTemplate"] = "[{Level}]RequestPath:{RequestPath} => {SourceContext} => {Message} {Exception}{NewLine}"; } var handlers = ReflectionHelper .GetNonPublicInstanceFieldValue <List <Type> >(instance, "Handlers"); handlers.Add(typeof(GlobalErrorHandler)); if (includeDistributedTracing) { handlers.Add(typeof(InboundBeginRequestObserverHandler)); handlers.Add(typeof(InboundEndRequestObserverHandler)); handlers.Add(typeof(InboundErrorRequestObserverHandler)); handlers.Add(typeof(ScopedLoggingHandler)); } ReflectionHelper .GetNonPublicInstanceFieldValue <List <Action <HostBuilderContext, ILoggingBuilder> > >(instance, "ConfigureLoggingDelegates") .Add((builderContext, loggingBuilder) => { loggingBuilder.ClearProviders(); var loggerConfiguration = new LoggerConfiguration() .ReadFrom.Configuration(builderContext.Configuration) .Enrich.FromLogContext() .Filter.ByExcluding("Contains(@Message, 'cloudfoundryapplication')"); var serilogOptions = new SerilogOptions(builderContext.Configuration); var levelSwitch = new LoggingLevelSwitch(serilogOptions.MinimumLevel.Default); loggerConfiguration.MinimumLevel.ControlledBy(levelSwitch); var logger = loggerConfiguration.CreateLogger(); Log.Logger = logger; loggingBuilder.Services.AddSingleton <IDynamicLoggerProvider>(sp => new SerilogDynamicProvider(sp.GetRequiredService <IConfiguration>(), serilogOptions, logger, levelSwitch)); loggingBuilder.Services.AddSingleton <ILoggerFactory>(sp => new SerilogDynamicLoggerFactory(sp.GetRequiredService <IDynamicLoggerProvider>())); if (includeDistributedTracing) { loggingBuilder.Services.AddDefaultDiagnosticsDependencies(builderContext.Configuration); } if (addDebug) { loggingBuilder.AddDebug(); } }); instance.AddDefaultConfigurations(); instance.AddConfigServer(); return(instance); }