public void ShouldRespectDynamicLevelChanges() { using (var logger = new LoggerConfiguration() .ReadFrom .Configuration(new ConfigurationBuilder().Add(_configSource).Build()) .CreateLogger()) { DummyConsoleSink.Emitted.Clear(); logger.Write(Some.DebugEvent()); Assert.Empty(DummyConsoleSink.Emitted); DummyConsoleSink.Emitted.Clear(); UpdateConfig(minimumLevel: LogEventLevel.Debug); logger.Write(Some.DebugEvent()); Assert.Empty(DummyConsoleSink.Emitted); DummyConsoleSink.Emitted.Clear(); UpdateConfig(switchLevel: LogEventLevel.Debug); logger.Write(Some.DebugEvent()); logger.ForContext(Constants.SourceContextPropertyName, "Root.Test").Write(Some.DebugEvent()); Assert.Single(DummyConsoleSink.Emitted); DummyConsoleSink.Emitted.Clear(); UpdateConfig(overrideLevel: LogEventLevel.Debug); logger.ForContext(Constants.SourceContextPropertyName, "Root.Test").Write(Some.DebugEvent()); Assert.Single(DummyConsoleSink.Emitted); } }
public void ReloadableLoggerRespectsMinimumLevelOverrides() { var emittedEvents = new List <LogEvent>(); var logger = new LoggerConfiguration() .MinimumLevel.Override("Test", LogEventLevel.Warning) .WriteTo.Sink(new ListSink(emittedEvents)) .CreateBootstrapLogger(); var limited = logger .ForContext("X", 1) .ForContext(Constants.SourceContextPropertyName, "Test.Stuff"); var notLimited = logger.ForContext <ReloadableLoggerTests>(); foreach (var context in new[] { limited, notLimited }) { // Suppressed by both sinks context.Debug("First"); // Suppressed by the limited logger context.Information("Second"); // Emitted by both loggers context.Warning("Third"); } Assert.Equal(3, emittedEvents.Count); Assert.Equal(2, emittedEvents.Count(le => le.Level == LogEventLevel.Warning)); }
public void Fact2() { LoggingLevelSwitch category1Switch = new LoggingLevelSwitch(); bool CategoriesBelowCertainLevel(LogEvent e) { return(Matching.FromSource("Category1").Invoke(e) && e.Level < category1Switch.MinimumLevel); } Logger logger = new LoggerConfiguration() .Enrich.FromLogContext() .MinimumLevel.Verbose() .Filter.ByExcluding(CategoriesBelowCertainLevel) //.AuditTo.Sink() .WriteTo.Logger(configuration => configuration .MinimumLevel.Warning() .MinimumLevel.Override("Category1", LogEventLevel.Information) .WriteTo.File("file1.log")) .WriteTo.Console() .CreateLogger(); Serilog.ILogger category1Logger = logger.ForContext(Constants.SourceContextPropertyName, "Category1"); Serilog.ILogger category2Logger = logger.ForContext(Constants.SourceContextPropertyName, "Category2"); category1Logger.Information("visible"); category2Logger.Information("invisible"); category1Logger.Information("invisible"); category2Logger.Information("visible"); }
public void ReloadableLoggersRecordEnrichment() { var emittedEvents = new List <LogEvent>(); var logger = new LoggerConfiguration() .WriteTo.Sink(new ListSink(emittedEvents)) .CreateBootstrapLogger(); var outer = logger .ForContext("A", new object()); var inner = outer.ForContext("B", "test"); inner.Information("First"); logger.Reload(lc => lc.WriteTo.Sink(new ListSink(emittedEvents))); inner.Information("Second"); logger.Freeze(); inner.Information("Third"); outer.ForContext("B", "test").Information("Fourth"); logger.ForContext("A", new object()) .ForContext("B", "test") .Information("Fifth"); Assert.Equal(5, emittedEvents.Count); Assert.All(emittedEvents, e => Assert.Equal(2, e.Properties.Count)); }
private static void Main(string[] args) { using (var log = new LoggerConfiguration() .MinimumLevel.Debug() // 要使用LogContext.PushProperty, Enrich.FromLogcontext()為必要 .Enrich.FromLogContext() .Enrich.WithProperty("Application", "Demo") // Package: Serilog.Enrichers.Environment .Enrich.WithMachineName() // Package: Serilog.Sinks.Console .WriteTo.Console() // Package: Serilog.Sinks.File .WriteTo.File("./log/log.txt") .WriteTo.File(new JsonFormatter(), "./log/log.json") // Package: Serilog.Formatting.Compact .WriteTo.File(new CompactJsonFormatter(), "./log/log.clef") .CreateLogger()) { try { throw new Exception("exception test"); } catch (Exception ex) { log.Error(ex, "Error Happened: {message}", ex.Message); } log.Debug("Test"); log.Information("Hello, Serilog!"); log.Warning("Goodbye, Serilog."); // 加入特定property var specialLog = log.ForContext("Customer", "Mike"); specialLog.Warning("A very rich man! balance: {balance} millions", 100); // 以某個Class為Property (property name: SourceProperty) var contextLog = log.ForContext <SomeContext>(); contextLog.Warning("context log"); // 動態加入property using (LogContext.PushProperty("OrderNumber", "ABC123")) { using (LogContext.PushProperty("TransactionId", "T12345")) { log.Debug("this log has TransactionId"); using (LogContext.PushProperty("OrderNumber", "ABC123")) { log.Debug("this log has OrderNumber"); } } log.Debug("this log has no TransactionId"); } log.Debug("this log has no OrderNumber"); } }
public void LowerMinimumLevelOverridesArePropagated() { var sink = new CollectingSink(); var logger = new LoggerConfiguration() .MinimumLevel.Error() .MinimumLevel.Override("Microsoft", LogEventLevel.Debug) .WriteTo.Sink(sink) .CreateLogger(); logger.Write(Some.InformationEvent()); logger.ForContext(Constants.SourceContextPropertyName, "Microsoft.AspNet.Something").Write(Some.InformationEvent()); logger.ForContext <LoggerConfigurationTests>().Write(Some.InformationEvent()); Assert.Single(sink.Events); }
public void SpecifyingMinimumLevelOverridesInWriteToLoggerWritesWarningToSelfLog() { var outputs = new List <string>(); using (TemporarySelfLog.SaveTo(outputs)) { var subSink = new CollectingSink(); var subLogger = new LoggerConfiguration() .MinimumLevel.Verbose() .MinimumLevel.Override("Foo.Bar", Debug) .WriteTo.Sink(subSink) .CreateLogger(); var logger = new LoggerConfiguration() .MinimumLevel.Verbose() .MinimumLevel.Override("Foo.Bar", Warning) .WriteTo.Logger(subLogger) .CreateLogger(); var contextLogger = logger.ForContext(Constants.SourceContextPropertyName, "Foo.Bar"); contextLogger.Write(Some.InformationEvent()); } Assert.EndsWith("Minimum level overrides are not supported on sub-loggers " + "and may be removed completely in a future version.", outputs.FirstOrDefault() ?? ""); }
public void TestMinimumLevelOverrides() { var settings = new Dictionary <string, string> { ["minimum-level:override:System"] = "Warning", }; LogEvent evt = null; var log = new LoggerConfiguration() .ReadFrom.KeyValuePairs(settings) .WriteTo.Sink(new DelegatingSink(e => evt = e)) .CreateLogger(); var systemLogger = log.ForContext <WeakReference>(); systemLogger.Write(Some.InformationEvent()); Assert.Null(evt); systemLogger.Warning("Bad things"); Assert.NotNull(evt); evt = null; log.Write(Some.InformationEvent()); Assert.NotNull(evt); }
static void JsonFormattingExample() { using var log = new LoggerConfiguration() .Enrich.WithProperty("Application", "Example") .WriteTo.Console(new ExpressionTemplate( "{ {@t, @mt, @l: if @l = 'Information' then undefined() else @l, @x, ..@p} }\n")) .CreateLogger(); log.Information("Running {Example}", nameof(JsonFormattingExample)); log.ForContext <Program>() .Information("Cart contains {@Items}", new[] { "Tea", "Coffee" }); log.ForContext <Program>() .Warning("Cart is empty"); }
public void TestMinimumLevelOverrides() { var settings = new Dictionary <string, string> { ["minimum-level:override:Microsoft"] = "Warning", }; LogEvent evt = null; var log = new LoggerConfiguration() .ReadFrom.KeyValuePairs(settings) .WriteTo.Sink(new DelegatingSink(e => evt = e)) .CreateLogger(); var microsoftLogger = log.ForContext <Microsoft.Extensions.Testing.Abstractions.FullPdbReader>(); microsoftLogger.Write(Some.InformationEvent()); Assert.Null(evt); microsoftLogger.Warning("Bad things"); Assert.NotNull(evt); evt = null; log.Write(Some.InformationEvent()); Assert.NotNull(evt); }
public void Fact3() { DummySink sink = new DummySink(); LoggerSourceContextLevelOverrides switches = new LoggerSourceContextLevelOverrides(LogEventLevel.Warning, KeyValuePair.Create("A", LogEventLevel.Debug), KeyValuePair.Create("2", LogEventLevel.Debug), KeyValuePair.Create("3", LogEventLevel.Debug), KeyValuePair.Create("4", LogEventLevel.Debug), KeyValuePair.Create("5", LogEventLevel.Debug), KeyValuePair.Create("6", LogEventLevel.Debug), KeyValuePair.Create("7", LogEventLevel.Debug), KeyValuePair.Create("8", LogEventLevel.Debug), KeyValuePair.Create("9", LogEventLevel.Debug), KeyValuePair.Create("10", LogEventLevel.Debug) ); Logger logger = new LoggerConfiguration() .Filter().MinimumLevel() .WriteTo.Logger(c => c .Filter().Overrides(switches) .WriteTo.Sink(sink)) .CreateLogger(); Logger defaultLogger = new LoggerConfiguration() .Filter().MinimumLevel() .WriteTo.Logger(c => c .Filter().Overrides(switches) .WriteTo.Sink(sink)) .CreateLogger(); Serilog.ILogger abLogger = logger.ForContext(Constants.SourceContextPropertyName, "A.B"); Serilog.ILogger bLogger = logger.ForContext(Constants.SourceContextPropertyName, "B"); for (int i = 0; i < 100_000; i++) { bLogger.Information("b"); } Assert.Empty(sink.Events); sink.Events.Clear(); for (int i = 0; i < 100_000; i++) { abLogger.Debug("ab"); } Assert.Equal(100000, sink.Events.Count); sink.Events.Clear(); }
public void FilterWithIsAppliedWithCustomFilter() { LogEvent evt = null; var log = new LoggerConfiguration() .ReadFrom.KeyValuePairs(new Dictionary <string, string> { ["using:TestDummies"] = typeof(DummyLoggerConfigurationExtensions).GetTypeInfo().Assembly.FullName, ["filter:With.filter"] = typeof(DummyAnonymousUserFilter).AssemblyQualifiedName }) .WriteTo.Sink(new DelegatingSink(e => evt = e)) .CreateLogger(); log.ForContext("User", "anonymous").Write(Some.InformationEvent()); Assert.Null(evt); log.ForContext("User", "the user").Write(Some.InformationEvent()); Assert.NotNull(evt); }
public LogEventConstructionBenchmark() { _sink = new CapturingSink(); var underlyingLogger = new LoggerConfiguration().WriteTo.Sink(_sink).CreateLogger(); _serilogContextualLogger = underlyingLogger.ForContext <LogEventConstructionBenchmark>(); _melLogger = new SerilogLoggerProvider(underlyingLogger).CreateLogger(GetType().FullName); }
/// <summary> /// Creates a logger using the application configuration /// </summary> /// <param name="configuration">The configuration to read from</param> /// <returns>An logger instance</returns> private static ILogger CreateLogger(IConfiguration configuration) { var logger = new LoggerConfiguration() .ReadFrom.Configuration(configuration) .CreateLogger(); Log.Logger = logger; return(logger.ForContext <Program>()); }
static void PipelineComponentExample() { using var log = new LoggerConfiguration() .Enrich.WithProperty("Application", "Example") .Enrich.WithComputed("FirstItem", "coalesce(Items[0], '<empty>')") .Enrich.WithComputed("SourceContext", "coalesce(Substring(SourceContext, LastIndexOf(SourceContext, '.') + 1), '<no source>')") .Filter.ByIncludingOnly("Items is null or Items[?] like 'C%'") .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3} ({SourceContext})] {Message:lj} (first item is {FirstItem}){NewLine}{Exception}") .CreateLogger(); log.Information("Running {Example}", nameof(PipelineComponentExample)); log.ForContext <Program>() .Information("Cart contains {@Items}", new[] { "Tea", "Coffee" }); log.ForContext <Program>() .Information("Cart contains {@Items}", new[] { "Apricots" }); }
public void ExceptionsThrownByAuditSinksArePropagatedFromChildLoggers() { var logger = new LoggerConfiguration() .AuditTo.Sink(new DelegatingSink(e => { throw new Exception("Boom!"); })) .CreateLogger(); Assert.Throws <AggregateException>(() => logger .ForContext <LoggerConfigurationTests>() .Write(Some.InformationEvent())); }
//TODO: extract common projects in to shared stages and build then cache static async Task Main(string[] args) { await DockerfileGenerator.WriteResources(); await Parser.Default.ParseArguments <CmdOptions>(args) .WithParsedAsync <CmdOptions>(async o => { o.OriginalArgs = string.Join(" ", args); var logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Console(o.Verbose ? LogEventLevel.Verbose : LogEventLevel.Warning) .CreateLogger(); try { if (!o.Validate(logger.ForContext <CmdOptions>())) { Environment.ExitCode = 101; return; } o.OutputArgs(logger.ForContext <CmdOptions>()); DockerfileGenerator generator = new DockerfileGenerator(o.Template, logger.ForContext <DockerfileGenerator>()); if (generator.InvalidTemplate) { Environment.ExitCode = 102; return; } using var solutionsData = new SolutionData(o.SlnFile, logger); var testProvider = new TestProvider(logger.ForContext <TestProvider>(), o.ProjectsToTest, o.AutoTestExclude, o.AutoTestDepth); await execute(o, generator, solutionsData, testProvider, logger); } catch (Exception ex) { logger.Fatal(ex, "Exception thrown in Main"); throw; } }); }
public static Logger 添加上下文() { var logger = new LoggerConfiguration() .Enrich.WithProperty("Version", "1.0.0") .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") .CreateLogger(); var subLogger = logger.ForContext("Version", "1.0.1");//修改了Properties中的Version信息 subLogger.Information("in {Version}"); return(logger); }
public static void Main(string[] args) { var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true) .Build(); var logger = new LoggerConfiguration() .ReadFrom.Configuration(configuration) .CreateLogger(); do { logger.ForContext <Program>().Information("Hello, world!"); logger.ForContext(Constants.SourceContextPropertyName, "Microsoft").Warning("Hello, world!"); logger.ForContext(Constants.SourceContextPropertyName, "MyApp.Something.Tricky").Verbose("Hello, world!"); Console.WriteLine(); }while (Console.ReadKey().KeyChar != 'q'); }
public void CachingReloadableLoggerRemainsUsableAfterFreezing() { var logger = new LoggerConfiguration().CreateBootstrapLogger(); var contextual = logger.ForContext <ReloadableLoggerTests>(); contextual.Information("First"); logger.Reload(c => c); logger.Freeze(); contextual.Information("Second"); contextual.Information("Third"); contextual.Information("Fourth"); // No crash :-) }
static void TextFormattingExample() { using var log = new LoggerConfiguration() .WriteTo.Console(new ExpressionTemplate( "[{@t:HH:mm:ss} " + "{@l:u3} " + "({coalesce(Substring(SourceContext, LastIndexOf(SourceContext, '.') + 1), '<no source>')})] " + "{@m} " + "(first item is {coalesce(Items[0], '<empty>')})" + "\n" + "{@x}")) .CreateLogger(); log.Information("Running {Example}", nameof(TextFormattingExample)); log.ForContext <Program>() .Information("Cart contains {@Items}", new[] { "Tea", "Coffee" }); log.ForContext <Program>() .Information("Cart contains {@Items}", new[] { "Apricots" }); }
public void Can_Specify_Category_As_Missing_Property() { var methodInfo = nameof(Can_Specify_Category_As_Property); using (var log = new LoggerConfiguration() .WriteTo.Loupe(categoryPropertyName: "CategoryWeWillNotFind") .CreateLogger()) { log.ForContext("LoupeCategoryProperty", methodInfo + ".Debug") .Debug("This is a debug message about {methodInfo} which should be in the default category", methodInfo); log.ForContext("LoupeCategoryProperty", methodInfo + ".Verbose") .Verbose("This is a verbose message about {methodInfo} which should be in the default category", methodInfo); log.ForContext("LoupeCategoryProperty", methodInfo + ".Info") .Information("This is an informational message about {methodInfo} which should be in the default category", methodInfo); log.ForContext("LoupeCategoryProperty", methodInfo + ".Error") .Error("This is an error message about {methodInfo} which should be in the default category", methodInfo); } }
public static void Main(string[] args) { var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true) .Build(); var logger = new LoggerConfiguration() .ReadFrom.Configuration(configuration) .CreateLogger(); logger.Information("Args: {a}", args); do { logger.ForContext <Program>().Information("Hello, world!"); logger.ForContext <Program>().Error("Hello, world!"); logger.ForContext(Constants.SourceContextPropertyName, "Microsoft").Warning("Hello, world!"); logger.ForContext(Constants.SourceContextPropertyName, "Microsoft").Error("Hello, world!"); logger.ForContext(Constants.SourceContextPropertyName, "MyApp.Something.Tricky").Verbose("Hello, world!"); logger.Information("Destructure with max object nesting depth:\n{@NestedObject}", new { FiveDeep = new { Two = new { Three = new { Four = new { Five = "the end" } } } } }); logger.Information("Destructure with max string length:\n{@LongString}", new { TwentyChars = "0123456789abcdefghij" }); logger.Information("Destructure with max collection count:\n{@BigData}", new { TenItems = new[] { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" } }); logger.Information("Destructure with policy to strip password:\n{@LoginData}", new LoginData { Username = "******", Password = "******" }); Console.WriteLine("\nPress \"q\" to quit, or any other key to run again.\n"); }while(!args.Contains("--run-once") && (Console.ReadKey().KeyChar != 'q')); }
public void EventsCanBeExcludedBySource() { var written = false; var log = new LoggerConfiguration() .Filter.ByExcluding(Matching.FromSource<MatchingTests>()) .WriteTo.Sink(new DelegatingSink(e => written = true)) .CreateLogger(); var sourceContext = log.ForContext<MatchingTests>(); sourceContext.Write(Some.InformationEvent()); Assert.False(written); }
public void Can_Specify_Category_As_Property() { var methodInfo = nameof(Can_Specify_Category_As_Property); var categoryPropertyName = "LogCategory"; using (var log = new LoggerConfiguration() .WriteTo.Loupe(categoryPropertyName: categoryPropertyName) .CreateLogger()) { log.ForContext(categoryPropertyName, methodInfo + ".Debug") .Debug("This is a debug message about {methodInfo} which should be in category {" + categoryPropertyName + "}", methodInfo); log.ForContext(categoryPropertyName, methodInfo + ".Verbose") .Verbose("This is a verbose message about {methodInfo} which should be in category {" + categoryPropertyName + "}", methodInfo); log.ForContext(categoryPropertyName, methodInfo + ".Info") .Information("This is an informational message about {methodInfo} which should be in category {" + categoryPropertyName + "}", methodInfo); log.ForContext(categoryPropertyName, methodInfo + ".Error") .Error("This is an error message about {methodInfo} which should be in category {" + categoryPropertyName + "}", methodInfo); } }
public void EventsCanBeExcludedBySource() { var written = false; var log = new LoggerConfiguration() .Filter.ByExcluding(Matching.FromSource <MatchingTests>()) .WriteTo.Sink(new DelegatingSink(e => written = true)) .CreateLogger(); var sourceContext = log.ForContext <MatchingTests>(); sourceContext.Write(Some.InformationEvent()); Assert.False(written); }
public void ShouldNotEnrichLogEventsWhenMinLevelIsHigherThanProvidedLogLevel(LogEventLevel logMinLevel, LogEventLevel propertLogLevel) { var propValue = Guid.NewGuid(); var propKey = Some.String(); var sink = new CollectingSink(); var logger = new LoggerConfiguration() .MinimumLevel.Is(logMinLevel) .WriteTo.Sink(sink) .CreateLogger(); logger.ForContext(propertLogLevel, propKey, propValue) .Write(logMinLevel, string.Empty); Assert.True(!sink.SingleEvent.Properties.ContainsKey(propKey)); }
private static void ConfigureLogger(IConfiguration config) { var logger = new LoggerConfiguration() .MinimumLevel.Debug() .Enrich.FromLogContext() .ReadFrom.Configuration(config) .WriteTo.Console() .WriteTo.File( new RenderedCompactJsonFormatter(), "azure-storage-migrator.log", rollOnFileSizeLimit: true, fileSizeLimitBytes: 10 * 1024 * 1024 /*10 MB*/, retainedFileCountLimit: 10) .CreateLogger(); Log.Logger = logger.ForContext("SourceContext", "AzureStorageMigrator"); }
public void EventsAreWrittenToTheAliyunLog() { var targetFramework = typeof(ILogServiceClient) .Assembly .GetCustomAttribute <TargetFrameworkAttribute>() .FrameworkName; var stats = new { DateTime.Now, RuntimeInformation.OSDescription, RuntimeInformation.OSArchitecture, RuntimeInformation.ProcessArchitecture, TargetFramework = targetFramework }; var client = LogServiceClientBuilders .HttpBuilder .Endpoint("https://cn-qingdao.log.aliyuncs.com", project) .Credential(accessKeyId, accessKey) .Build(); var log = new LoggerConfiguration() .WriteTo.AliyunLog(client, logStore, logTags: new Dictionary <string, string> { { "Env", "UnitTest" }, { "App", "Serilog.Sinks.AliyunLog" } }) .MinimumLevel.Verbose() .CreateLogger(); log.Information("this is info message {@stats}", stats); log.ForContext <AliyunLogSinkTest>().Error(new NotImplementedException(), "this is error message with context {@stats}", stats); log.Debug("{@stats}", stats); if (Debugger.IsAttached) { SpinWait.SpinUntil(() => false); } else { SpinWait.SpinUntil(() => false, 1000 * 60 * 1); } }
private static void Main() { var logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.ColoredConsole( outputTemplate: "{Timestamp:HH:mm:ss} ({ThreadId}) [{Level}] {Message:l}{NewLine:l}{Exception:l}") .WriteTo.Trace() .Enrich.WithProperty("App", "Test Harness") .Enrich.With(new ThreadIdEnricher(), new MachineNameEnricher()) .CreateLogger(); logger.Information("Just biting {Fruit} number {Count}", "Apple", 12); logger.ForContext <Program>().Information("Just biting {Fruit} number {Count:0000}", "Apple", 12); using (logger.BeginTimedOperation("Time a thread sleep for 2 seconds.")) { Thread.Sleep(1000); using (logger.BeginTimedOperation("And inside we try a Task.Delay for 2 seconds.")) { Task.Delay(2000).Wait(); } Thread.Sleep(1000); } using (logger.BeginTimedOperation("Using a passed in identifier", "test-loop")) { var a = ""; for (int i = 0; i < 1000; i++) { a += "b"; } } // Exceed a limit using (logger.BeginTimedOperation("This should execute within 1 second.", null, LogEventLevel.Debug, TimeSpan.FromSeconds(1))) { Thread.Sleep(1100); } Console.ReadKey(true); }
public void LoggingLevelSwitchCanBeUsedForMinimumLevelOverrides() { var settings = new Dictionary <string, string> { ["minimum-level"] = "Debug", ["level-switch:$specificSwitch"] = "Warning", ["minimum-level:override:System"] = "$specificSwitch", ["using:TestDummies"] = typeof(DummyLoggerConfigurationExtensions).GetTypeInfo().Assembly.FullName, ["write-to:DummyWithLevelSwitch.controlLevelSwitch"] = "$specificSwitch" }; LogEvent evt = null; var log = new LoggerConfiguration() .ReadFrom.KeyValuePairs(settings) .WriteTo.Sink(new DelegatingSink(e => evt = e)) .CreateLogger(); var systemLogger = log.ForContext(Constants.SourceContextPropertyName, "System.Bar"); log.Write(Some.InformationEvent()); Assert.False(evt is null, "Minimum level is Debug. It should log Information messages"); evt = null; // ReSharper disable HeuristicUnreachableCode systemLogger.Write(Some.InformationEvent()); Assert.True(evt is null, "LoggingLevelSwitch initial level was Warning for logger System.*. It should not log Information messages for SourceContext System.Bar"); systemLogger.Write(Some.WarningEvent()); Assert.False(evt is null, "LoggingLevelSwitch initial level was Warning for logger System.*. It should log Warning messages for SourceContext System.Bar"); evt = null; var controlSwitch = DummyWithLevelSwitchSink.ControlLevelSwitch; controlSwitch.MinimumLevel = LogEventLevel.Information; systemLogger.Write(Some.InformationEvent()); Assert.False(evt is null, "LoggingLevelSwitch level was changed to Information for logger System.*. It should now log Information events for SourceContext System.Bar."); // ReSharper restore HeuristicUnreachableCode }
public void ExceptionsThrownByAuditSinksArePropagatedFromChildLoggers() { var logger = new LoggerConfiguration() .AuditTo.Sink(new DelegatingSink(e => { throw new Exception("Boom!"); })) .CreateLogger(); Assert.Throws<AggregateException>(() => logger .ForContext<LoggerConfigurationTests>() .Write(Some.InformationEvent())); }
public void LowerMinimumLevelOverridesArePropagated() { var sink = new CollectingSink(); var logger = new LoggerConfiguration() .MinimumLevel.Error() .MinimumLevel.Override("Microsoft", LogEventLevel.Debug) .WriteTo.Sink(sink) .CreateLogger(); logger.Write(Some.InformationEvent()); logger.ForContext(Serilog.Core.Constants.SourceContextPropertyName, "Microsoft.AspNet.Something").Write(Some.InformationEvent()); logger.ForContext<LoggerConfigurationTests>().Write(Some.InformationEvent()); Assert.Equal(1, sink.Events.Count); }