From 5e90f2de619b65616577a1eb7622bdf03ac19d93 Mon Sep 17 00:00:00 2001 From: Ivan Maximov Date: Tue, 9 Aug 2022 11:02:31 +0300 Subject: [PATCH] Introduce file-scoped namespaces (#1725) --- .editorconfig | 3 + .../AllocationsBenchmark.cs | 147 ++++++------ .../BindingBenchmark.cs | 85 ++++--- test/Serilog.PerformanceTests/Harness.cs | 137 ++++++----- .../LevelControlBenchmark.cs | 95 ++++---- .../LogContextEnrichmentBenchmark.cs | 75 +++--- .../MessageTemplateCacheBenchmark_Cached.cs | 101 ++++---- .../MessageTemplateCacheBenchmark_Leaking.cs | 85 ++++--- .../MessageTemplateParsingBenchmark.cs | 46 ++-- .../MessageTemplateRenderingBenchmark.cs | 44 ++-- .../NestedLoggerCreationBenchmark.cs | 59 +++-- .../NestedLoggerLatencyBenchmark.cs | 51 ++-- .../OutputTemplateRenderingBenchmark.cs | 32 +-- .../PipelineBenchmark.cs | 46 ++-- .../SourceContextMatchBenchmark.cs | 125 +++++----- .../ConcurrentDictionaryTemplateCache.cs | 65 +++-- .../Support/DictionaryMessageTemplateCache.cs | 71 +++--- .../Support/NoOpMessageTemplateParser.cs | 17 +- .../Support/NullSink.cs | 11 +- .../Support/NullTextWriter.cs | 223 +++++++++--------- test/Serilog.PerformanceTests/Support/Some.cs | 15 +- test/TestDummies/Console/DummyConsoleSink.cs | 21 +- .../Console/Themes/ConcreteConsoleTheme.cs | 7 +- .../Console/Themes/ConsoleTheme.cs | 9 +- .../Console/Themes/ConsoleThemes.cs | 9 +- .../Console/Themes/EmptyConsoleTheme.cs | 7 +- test/TestDummies/DummyAnonymousUserFilter.cs | 23 +- ...DummyHardCodedStringDestructuringPolicy.cs | 27 +-- .../DummyLoggerConfigurationExtensions.cs | 145 ++++++------ .../DummyReduceVersionToMajorPolicy.cs | 21 +- test/TestDummies/DummyRollingFileAuditSink.cs | 27 +-- test/TestDummies/DummyRollingFileSink.cs | 27 +-- test/TestDummies/DummyThreadIdEnricher.cs | 15 +- test/TestDummies/DummyWithLevelSwitchSink.cs | 31 ++- test/TestDummies/DummyWrappingSink.cs | 39 ++- 35 files changed, 957 insertions(+), 984 deletions(-) diff --git a/.editorconfig b/.editorconfig index fe3a2de34..9d54ae139 100644 --- a/.editorconfig +++ b/.editorconfig @@ -16,3 +16,6 @@ end_of_line = lf [*.{cmd, bat}] end_of_line = crlf + +# C# formatting settings - Namespace options +csharp_style_namespace_declarations = file_scoped:suggestion diff --git a/test/Serilog.PerformanceTests/AllocationsBenchmark.cs b/test/Serilog.PerformanceTests/AllocationsBenchmark.cs index 85201d6ec..213c50699 100644 --- a/test/Serilog.PerformanceTests/AllocationsBenchmark.cs +++ b/test/Serilog.PerformanceTests/AllocationsBenchmark.cs @@ -6,100 +6,99 @@ using System.Collections.Generic; using System.Linq; -namespace Serilog.PerformanceTests +namespace Serilog.PerformanceTests; + +[MemoryDiagnoser] +public class AllocationsBenchmark { - [MemoryDiagnoser] - public class AllocationsBenchmark - { - readonly ILogger _logger; - readonly ILogger _enrichedLogger; - readonly LogEvent _emptyEvent; - readonly object _dictionaryValue; - readonly object _anonymousObject; - readonly object _sequence; + readonly ILogger _logger; + readonly ILogger _enrichedLogger; + readonly LogEvent _emptyEvent; + readonly object _dictionaryValue; + readonly object _anonymousObject; + readonly object _sequence; - public AllocationsBenchmark() - { - _logger = new LoggerConfiguration().CreateLogger(); + public AllocationsBenchmark() + { + _logger = new LoggerConfiguration().CreateLogger(); - _enrichedLogger = _logger.ForContext(new PropertyEnricher("Prop", "Value")); + _enrichedLogger = _logger.ForContext(new PropertyEnricher("Prop", "Value")); - _emptyEvent = new( - DateTimeOffset.Now, - LogEventLevel.Information, - null, - new(Enumerable.Empty()), - Enumerable.Empty()); + _emptyEvent = new( + DateTimeOffset.Now, + LogEventLevel.Information, + null, + new(Enumerable.Empty()), + Enumerable.Empty()); - _anonymousObject = new + _anonymousObject = new + { + Level11 = "Val1", + Level12 = new { - Level11 = "Val1", - Level12 = new + Level21 = (int?)42, + Level22 = new { - Level21 = (int?)42, - Level22 = new + Level31 = System.Reflection.BindingFlags.FlattenHierarchy, + Level32 = new { - Level31 = System.Reflection.BindingFlags.FlattenHierarchy, - Level32 = new - { - X = 3, - Y = "4", - Z = (short?)5 - } + X = 3, + Y = "4", + Z = (short?)5 } } - }; + } + }; - _dictionaryValue = new Dictionary { - { "Level11", "Val1" }, - { "Level12", new Dictionary { - { "Level21", (int?)42 }, - { "Level22", new Dictionary { - { "Level31", System.Reflection.BindingFlags.FlattenHierarchy }, - { "Level32", new { X = 3, Y = "4", Z = (short?)5 } } - } + _dictionaryValue = new Dictionary { + { "Level11", "Val1" }, + { "Level12", new Dictionary { + { "Level21", (int?)42 }, + { "Level22", new Dictionary { + { "Level31", System.Reflection.BindingFlags.FlattenHierarchy }, + { "Level32", new { X = 3, Y = "4", Z = (short?)5 } } } } } - }; + } + }; - _sequence = new List { "1", 2, (int?)3, "4", (short)5 }; - } + _sequence = new List { "1", 2, (int?)3, "4", (short)5 }; + } - [Benchmark(Baseline = true)] - public void LogEmpty() - { - _logger.Write(_emptyEvent); - } + [Benchmark(Baseline = true)] + public void LogEmpty() + { + _logger.Write(_emptyEvent); + } - [Benchmark] - public void LogEmptyWithEnricher() - { - _enrichedLogger.Write(_emptyEvent); - } + [Benchmark] + public void LogEmptyWithEnricher() + { + _enrichedLogger.Write(_emptyEvent); + } - [Benchmark] - public void LogScalar() - { - _logger.Information("Template: {ScalarValue}", "42"); - } + [Benchmark] + public void LogScalar() + { + _logger.Information("Template: {ScalarValue}", "42"); + } - [Benchmark] - public void LogDictionary() - { - _logger.Information("Template: {DictionaryValue}", _dictionaryValue); - } + [Benchmark] + public void LogDictionary() + { + _logger.Information("Template: {DictionaryValue}", _dictionaryValue); + } - [Benchmark] - public void LogSequence() - { - _logger.Information("Template: {SequenceValue}", _sequence); - } + [Benchmark] + public void LogSequence() + { + _logger.Information("Template: {SequenceValue}", _sequence); + } - [Benchmark] - public void LogAnonymous() - { - _logger.Information("Template: {@AnonymousObject}.", _anonymousObject); - } + [Benchmark] + public void LogAnonymous() + { + _logger.Information("Template: {@AnonymousObject}.", _anonymousObject); } } diff --git a/test/Serilog.PerformanceTests/BindingBenchmark.cs b/test/Serilog.PerformanceTests/BindingBenchmark.cs index 4b3de448e..f5bbc55fb 100644 --- a/test/Serilog.PerformanceTests/BindingBenchmark.cs +++ b/test/Serilog.PerformanceTests/BindingBenchmark.cs @@ -17,56 +17,55 @@ using Serilog.Events; using Serilog.PerformanceTests.Support; -namespace Serilog.PerformanceTests +namespace Serilog.PerformanceTests; + +/// +/// Tests the cost of writing through the logging pipeline. +/// +[MemoryDiagnoser] +public class BindingBenchmark { - /// - /// Tests the cost of writing through the logging pipeline. - /// - [MemoryDiagnoser] - public class BindingBenchmark - { - const string - MT0 = "Zero", - MT1 = "Zero{A}one", - MT5 = "Zero{A}one{B}two{C}three{D}four{E}five"; + const string + MT0 = "Zero", + MT1 = "Zero{A}one", + MT5 = "Zero{A}one{B}two{C}three{D}four{E}five"; - ILogger _log = null!; - object[] _zero= null!, _one= null!, _five = null!; + ILogger _log = null!; + object[] _zero= null!, _one= null!, _five = null!; - [GlobalSetup] - public void Setup() - { - _log = new LoggerConfiguration() - .WriteTo.Sink(new NullSink()) - .CreateLogger(); + [GlobalSetup] + public void Setup() + { + _log = new LoggerConfiguration() + .WriteTo.Sink(new NullSink()) + .CreateLogger(); - _zero = new object[0]; - _one = new object[] { 1 }; - _five = new object[] { 1, 2, 3, 4, 5 }; - } + _zero = new object[0]; + _one = new object[] { 1 }; + _five = new object[] { 1, 2, 3, 4, 5 }; + } - // The benchmarks run p.Count() to force enumeration; this will be representative of how the API - // is consumed (there's not much point benchmarking time to return a lazy enumerator). + // The benchmarks run p.Count() to force enumeration; this will be representative of how the API + // is consumed (there's not much point benchmarking time to return a lazy enumerator). - [Benchmark(Baseline = true)] - public (MessageTemplate, int) BindZero() - { - _log.BindMessageTemplate(MT0, _zero, out var mt, out var p); - return (mt, p!.Count())!; - } + [Benchmark(Baseline = true)] + public (MessageTemplate, int) BindZero() + { + _log.BindMessageTemplate(MT0, _zero, out var mt, out var p); + return (mt, p!.Count())!; + } - [Benchmark] - public (MessageTemplate, int) BindOne() - { - _log.BindMessageTemplate(MT1, _one, out var mt, out var p); - return (mt, p!.Count())!; - } + [Benchmark] + public (MessageTemplate, int) BindOne() + { + _log.BindMessageTemplate(MT1, _one, out var mt, out var p); + return (mt, p!.Count())!; + } - [Benchmark] - public (MessageTemplate, int) BindFive() - { - _log.BindMessageTemplate(MT5, _five, out var mt, out var p); - return (mt, p!.Count())!; - } + [Benchmark] + public (MessageTemplate, int) BindFive() + { + _log.BindMessageTemplate(MT5, _five, out var mt, out var p); + return (mt, p!.Count())!; } } diff --git a/test/Serilog.PerformanceTests/Harness.cs b/test/Serilog.PerformanceTests/Harness.cs index f5e7b4f3e..11148af63 100644 --- a/test/Serilog.PerformanceTests/Harness.cs +++ b/test/Serilog.PerformanceTests/Harness.cs @@ -15,87 +15,86 @@ using BenchmarkDotNet.Running; using Xunit; -namespace Serilog.PerformanceTests +namespace Serilog.PerformanceTests; + +/// +/// Wrappers that make it easy to run benchmark suites through the dotnet test runner. +/// +/// +/// dotnet test -c Release -f netcoreapp3.1 --filter "FullyQualifiedName=Serilog.PerformanceTests.Harness.Allocations" +/// +public class Harness { - /// - /// Wrappers that make it easy to run benchmark suites through the dotnet test runner. - /// - /// - /// dotnet test -c Release -f netcoreapp3.1 --filter "FullyQualifiedName=Serilog.PerformanceTests.Harness.Allocations" - /// - public class Harness + [Fact] + public void SourceContextMatch() { - [Fact] - public void SourceContextMatch() - { - BenchmarkRunner.Run(); - } + BenchmarkRunner.Run(); + } - [Fact] - public void Allocations() - { - BenchmarkRunner.Run(); - } + [Fact] + public void Allocations() + { + BenchmarkRunner.Run(); + } - [Fact] - public void MessageTemplateCache() - { - BenchmarkRunner.Run(); - BenchmarkRunner.Run(); - } + [Fact] + public void MessageTemplateCache() + { + BenchmarkRunner.Run(); + BenchmarkRunner.Run(); + } - [Fact] - public void LogContextEnrichment() - { - BenchmarkRunner.Run(); - } + [Fact] + public void LogContextEnrichment() + { + BenchmarkRunner.Run(); + } - [Fact] - public void MessageTemplateParsing() - { - BenchmarkRunner.Run(); - } + [Fact] + public void MessageTemplateParsing() + { + BenchmarkRunner.Run(); + } - [Fact] - public void LevelControl() - { - BenchmarkRunner.Run(); - } + [Fact] + public void LevelControl() + { + BenchmarkRunner.Run(); + } - [Fact] - public void NestedLoggerCreation() - { - BenchmarkRunner.Run(); - } + [Fact] + public void NestedLoggerCreation() + { + BenchmarkRunner.Run(); + } - [Fact] - public void NestedLoggerLatency() - { - BenchmarkRunner.Run(); - } + [Fact] + public void NestedLoggerLatency() + { + BenchmarkRunner.Run(); + } - [Fact] - public void Pipeline() - { - BenchmarkRunner.Run(); - } + [Fact] + public void Pipeline() + { + BenchmarkRunner.Run(); + } - [Fact] - public void OutputTemplateRendering() - { - BenchmarkRunner.Run(); - } + [Fact] + public void OutputTemplateRendering() + { + BenchmarkRunner.Run(); + } - [Fact] - public void MessageTemplateRendering() - { - BenchmarkRunner.Run(); - } + [Fact] + public void MessageTemplateRendering() + { + BenchmarkRunner.Run(); + } - [Fact] - public void Binding() - { - BenchmarkRunner.Run(); - } + [Fact] + public void Binding() + { + BenchmarkRunner.Run(); } } diff --git a/test/Serilog.PerformanceTests/LevelControlBenchmark.cs b/test/Serilog.PerformanceTests/LevelControlBenchmark.cs index 2dbd1b606..69788215a 100644 --- a/test/Serilog.PerformanceTests/LevelControlBenchmark.cs +++ b/test/Serilog.PerformanceTests/LevelControlBenchmark.cs @@ -3,59 +3,58 @@ using Serilog.Events; using Serilog.PerformanceTests.Support; -namespace Serilog.PerformanceTests +namespace Serilog.PerformanceTests; + +/// +/// Tests the overhead of determining the active logging level. +/// +public class LevelControlBenchmark { - /// - /// Tests the overhead of determining the active logging level. - /// - public class LevelControlBenchmark - { - ILogger _off = null!, _levelSwitchOff = null!, _minLevel = null!, _levelSwitch = null!; - readonly LogEvent _event = Some.InformationEvent(); + ILogger _off = null!, _levelSwitchOff = null!, _minLevel = null!, _levelSwitch = null!; + readonly LogEvent _event = Some.InformationEvent(); - [GlobalSetup] - public void Setup() - { - _off = new LoggerConfiguration() - .MinimumLevel.Fatal() - .WriteTo.Sink(new NullSink()) - .CreateLogger(); - _levelSwitchOff = new LoggerConfiguration() - .MinimumLevel.ControlledBy(new LoggingLevelSwitch(LogEventLevel.Fatal)) - .WriteTo.Sink(new NullSink()) - .CreateLogger(); - _minLevel = new LoggerConfiguration() - .MinimumLevel.Information() - .WriteTo.Sink(new NullSink()) - .CreateLogger(); - _levelSwitch = new LoggerConfiguration() - .MinimumLevel.ControlledBy(new LoggingLevelSwitch(LogEventLevel.Information)) - .WriteTo.Sink(new NullSink()) - .CreateLogger(); - } + [GlobalSetup] + public void Setup() + { + _off = new LoggerConfiguration() + .MinimumLevel.Fatal() + .WriteTo.Sink(new NullSink()) + .CreateLogger(); + _levelSwitchOff = new LoggerConfiguration() + .MinimumLevel.ControlledBy(new LoggingLevelSwitch(LogEventLevel.Fatal)) + .WriteTo.Sink(new NullSink()) + .CreateLogger(); + _minLevel = new LoggerConfiguration() + .MinimumLevel.Information() + .WriteTo.Sink(new NullSink()) + .CreateLogger(); + _levelSwitch = new LoggerConfiguration() + .MinimumLevel.ControlledBy(new LoggingLevelSwitch(LogEventLevel.Information)) + .WriteTo.Sink(new NullSink()) + .CreateLogger(); + } - [Benchmark(Baseline = true)] - public void Off() - { - _off.Write(_event); - } + [Benchmark(Baseline = true)] + public void Off() + { + _off.Write(_event); + } - [Benchmark] - public void LevelSwitchOff() - { - _levelSwitchOff.Write(_event); - } + [Benchmark] + public void LevelSwitchOff() + { + _levelSwitchOff.Write(_event); + } - [Benchmark] - public void MinimumLevelOn() - { - _minLevel.Write(_event); - } + [Benchmark] + public void MinimumLevelOn() + { + _minLevel.Write(_event); + } - [Benchmark] - public void LevelSwitchOn() - { - _levelSwitch.Write(_event); - } + [Benchmark] + public void LevelSwitchOn() + { + _levelSwitch.Write(_event); } } diff --git a/test/Serilog.PerformanceTests/LogContextEnrichmentBenchmark.cs b/test/Serilog.PerformanceTests/LogContextEnrichmentBenchmark.cs index 164df642d..18562d535 100644 --- a/test/Serilog.PerformanceTests/LogContextEnrichmentBenchmark.cs +++ b/test/Serilog.PerformanceTests/LogContextEnrichmentBenchmark.cs @@ -3,56 +3,55 @@ using Serilog.Events; using Serilog.PerformanceTests.Support; -namespace Serilog.PerformanceTests +namespace Serilog.PerformanceTests; + +public class LogContextEnrichmentBenchmark { - public class LogContextEnrichmentBenchmark + ILogger _bare = null!, _enriched = null!; + readonly LogEvent _event = Some.InformationEvent(); + + [GlobalSetup] + public void Setup() { - ILogger _bare = null!, _enriched = null!; - readonly LogEvent _event = Some.InformationEvent(); + _bare = new LoggerConfiguration() + .WriteTo.Sink(new NullSink()) + .CreateLogger(); - [GlobalSetup] - public void Setup() - { - _bare = new LoggerConfiguration() - .WriteTo.Sink(new NullSink()) - .CreateLogger(); - - _enriched = new LoggerConfiguration() - .WriteTo.Sink(new NullSink()) - .Enrich.FromLogContext() - .CreateLogger(); - } + _enriched = new LoggerConfiguration() + .WriteTo.Sink(new NullSink()) + .Enrich.FromLogContext() + .CreateLogger(); + } - [Benchmark(Baseline = true)] - public void Bare() - { - _bare.Write(_event); - } + [Benchmark(Baseline = true)] + public void Bare() + { + _bare.Write(_event); + } - [Benchmark] - public void PushProperty() + [Benchmark] + public void PushProperty() + { + using (LogContext.PushProperty("A", "B")) { - using (LogContext.PushProperty("A", "B")) - { - } } + } - [Benchmark] - public void PushPropertyNested() + [Benchmark] + public void PushPropertyNested() + { + using (LogContext.PushProperty("A", "B")) + using (LogContext.PushProperty("C", "D")) { - using (LogContext.PushProperty("A", "B")) - using (LogContext.PushProperty("C", "D")) - { - } } + } - [Benchmark] - public void PushPropertyEnriched() + [Benchmark] + public void PushPropertyEnriched() + { + using (LogContext.PushProperty("A", "B")) { - using (LogContext.PushProperty("A", "B")) - { - _enriched.Write(_event); - } + _enriched.Write(_event); } } } diff --git a/test/Serilog.PerformanceTests/MessageTemplateCacheBenchmark/MessageTemplateCacheBenchmark_Cached.cs b/test/Serilog.PerformanceTests/MessageTemplateCacheBenchmark/MessageTemplateCacheBenchmark_Cached.cs index b69665ed1..3d11eae70 100644 --- a/test/Serilog.PerformanceTests/MessageTemplateCacheBenchmark/MessageTemplateCacheBenchmark_Cached.cs +++ b/test/Serilog.PerformanceTests/MessageTemplateCacheBenchmark/MessageTemplateCacheBenchmark_Cached.cs @@ -7,70 +7,69 @@ using Serilog.Core.Pipeline; using Serilog.PerformanceTests.Support; -namespace Serilog.PerformanceTests -{ - public class MessageTemplateCacheBenchmark_Cached - { - const string DefaultOutputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message}{NewLine}{Exception}"; +namespace Serilog.PerformanceTests; - List _templateList = null!; +public class MessageTemplateCacheBenchmark_Cached +{ + const string DefaultOutputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message}{NewLine}{Exception}"; - ConcurrentDictionaryMessageTemplateCache _concurrentCache = null!; - DictionaryMessageTemplateCache _dictionaryCache = null!; - MessageTemplateCache _hashtableCache = null!; + List _templateList = null!; - [Params(10, 20, 50, 100, 1000)] - public int Items { get; set; } + ConcurrentDictionaryMessageTemplateCache _concurrentCache = null!; + DictionaryMessageTemplateCache _dictionaryCache = null!; + MessageTemplateCache _hashtableCache = null!; - [Params(1, -1)] - public int MaxDegreeOfParallelism { get; set; } + [Params(10, 20, 50, 100, 1000)] + public int Items { get; set; } - [GlobalSetup] - public void Setup() - { - _templateList = Enumerable.Range(0, Items).Select(_ => $"{DefaultOutputTemplate}_{Guid.NewGuid()}").ToList(); + [Params(1, -1)] + public int MaxDegreeOfParallelism { get; set; } - _concurrentCache = new(NoOpMessageTemplateParser.Instance); - _dictionaryCache = new(NoOpMessageTemplateParser.Instance); - _hashtableCache = new(NoOpMessageTemplateParser.Instance); + [GlobalSetup] + public void Setup() + { + _templateList = Enumerable.Range(0, Items).Select(_ => $"{DefaultOutputTemplate}_{Guid.NewGuid()}").ToList(); - foreach (var t in _templateList) - { - _concurrentCache.Parse(t); - _dictionaryCache.Parse(t); - _hashtableCache.Parse(t); - } - } + _concurrentCache = new(NoOpMessageTemplateParser.Instance); + _dictionaryCache = new(NoOpMessageTemplateParser.Instance); + _hashtableCache = new(NoOpMessageTemplateParser.Instance); - [Benchmark(Baseline = true)] - public void Dictionary() + foreach (var t in _templateList) { - Run(() => _dictionaryCache); + _concurrentCache.Parse(t); + _dictionaryCache.Parse(t); + _hashtableCache.Parse(t); } + } - [Benchmark] - public void Hashtable() - { - Run(() => _hashtableCache); - } + [Benchmark(Baseline = true)] + public void Dictionary() + { + Run(() => _dictionaryCache); + } - [Benchmark] - public void Concurrent() - { - Run(() => _concurrentCache); - } + [Benchmark] + public void Hashtable() + { + Run(() => _hashtableCache); + } - void Run(Func cacheFactory) - where T : IMessageTemplateParser - { - var cache = cacheFactory(); - var iterations = Math.Min(10000, Items * 100); + [Benchmark] + public void Concurrent() + { + Run(() => _concurrentCache); + } - Parallel.For( - 0, - iterations, - new ParallelOptions { MaxDegreeOfParallelism = MaxDegreeOfParallelism }, - idx => cache.Parse(_templateList[idx % Items])); - } + void Run(Func cacheFactory) + where T : IMessageTemplateParser + { + var cache = cacheFactory(); + var iterations = Math.Min(10000, Items * 100); + + Parallel.For( + 0, + iterations, + new ParallelOptions { MaxDegreeOfParallelism = MaxDegreeOfParallelism }, + idx => cache.Parse(_templateList[idx % Items])); } } diff --git a/test/Serilog.PerformanceTests/MessageTemplateCacheBenchmark/MessageTemplateCacheBenchmark_Leaking.cs b/test/Serilog.PerformanceTests/MessageTemplateCacheBenchmark/MessageTemplateCacheBenchmark_Leaking.cs index d4131633e..550015113 100644 --- a/test/Serilog.PerformanceTests/MessageTemplateCacheBenchmark/MessageTemplateCacheBenchmark_Leaking.cs +++ b/test/Serilog.PerformanceTests/MessageTemplateCacheBenchmark/MessageTemplateCacheBenchmark_Leaking.cs @@ -7,59 +7,58 @@ using System.Linq; using System.Threading.Tasks; -namespace Serilog.PerformanceTests +namespace Serilog.PerformanceTests; + +public class MessageTemplateCacheBenchmark_Leaking { - public class MessageTemplateCacheBenchmark_Leaking - { - const string DefaultOutputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message}{NewLine}{Exception}"; - const int MaxCacheItems = 1000; + const string DefaultOutputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message}{NewLine}{Exception}"; + const int MaxCacheItems = 1000; - List _templateList = null!; + List _templateList = null!; - [Params(10000)] - public int Items { get; set; } + [Params(10000)] + public int Items { get; set; } - [Params(1, 10, 100, 1000)] - public int OverflowCount { get; set; } + [Params(1, 10, 100, 1000)] + public int OverflowCount { get; set; } - [Params(1, -1)] - public int MaxDegreeOfParallelism { get; set; } + [Params(1, -1)] + public int MaxDegreeOfParallelism { get; set; } - [GlobalSetup] - public void Setup() - { - _templateList = Enumerable.Range(0, Items).Select(_ => $"{DefaultOutputTemplate}_{Guid.NewGuid()}").ToList(); - } + [GlobalSetup] + public void Setup() + { + _templateList = Enumerable.Range(0, Items).Select(_ => $"{DefaultOutputTemplate}_{Guid.NewGuid()}").ToList(); + } - [Benchmark(Baseline = true)] - public void Dictionary() - { - Run(() => new DictionaryMessageTemplateCache(NoOpMessageTemplateParser.Instance)); - } + [Benchmark(Baseline = true)] + public void Dictionary() + { + Run(() => new DictionaryMessageTemplateCache(NoOpMessageTemplateParser.Instance)); + } - [Benchmark] - public void Hashtable() - { - Run(() => new MessageTemplateCache(NoOpMessageTemplateParser.Instance)); - } + [Benchmark] + public void Hashtable() + { + Run(() => new MessageTemplateCache(NoOpMessageTemplateParser.Instance)); + } - [Benchmark] - public void Concurrent() - { - Run(() => new ConcurrentDictionaryMessageTemplateCache(NoOpMessageTemplateParser.Instance)); - } + [Benchmark] + public void Concurrent() + { + Run(() => new ConcurrentDictionaryMessageTemplateCache(NoOpMessageTemplateParser.Instance)); + } - void Run(Func cacheFactory) - where T : IMessageTemplateParser - { - var cache = cacheFactory(); - var total = MaxCacheItems + OverflowCount; + void Run(Func cacheFactory) + where T : IMessageTemplateParser + { + var cache = cacheFactory(); + var total = MaxCacheItems + OverflowCount; - Parallel.For( - 0, - _templateList.Count, - new ParallelOptions { MaxDegreeOfParallelism = MaxDegreeOfParallelism }, - idx => cache.Parse(_templateList[idx % total])); - } + Parallel.For( + 0, + _templateList.Count, + new ParallelOptions { MaxDegreeOfParallelism = MaxDegreeOfParallelism }, + idx => cache.Parse(_templateList[idx % total])); } } diff --git a/test/Serilog.PerformanceTests/MessageTemplateParsingBenchmark.cs b/test/Serilog.PerformanceTests/MessageTemplateParsingBenchmark.cs index fa055fdad..5d61d472a 100644 --- a/test/Serilog.PerformanceTests/MessageTemplateParsingBenchmark.cs +++ b/test/Serilog.PerformanceTests/MessageTemplateParsingBenchmark.cs @@ -1,32 +1,32 @@ using BenchmarkDotNet.Attributes; using Serilog.Parsing; -namespace Serilog.PerformanceTests +namespace Serilog.PerformanceTests; + +/// +/// Tests the cost of parsing various message templates. +/// +[MemoryDiagnoser] +public class MessageTemplateParsingBenchmark { - /// - /// Tests the cost of parsing various message templates. - /// - public class MessageTemplateParsingBenchmark - { - MessageTemplateParser _parser = null!; - const string _DefaultConsoleOutputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message}{NewLine}{Exception}"; + MessageTemplateParser _parser = null!; + const string _DefaultConsoleOutputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message}{NewLine}{Exception}"; - [GlobalSetup] - public void Setup() - { - _parser = new MessageTemplateParser(); - } + [GlobalSetup] + public void Setup() + { + _parser = new MessageTemplateParser(); + } - [Benchmark(Baseline = true)] - public void EmptyTemplate() - { - _parser.Parse(""); - } + [Benchmark(Baseline = true)] + public void EmptyTemplate() + { + _parser.Parse(""); + } - [Benchmark] - public void DefaultConsoleOutputTemplate() - { - _parser.Parse(_DefaultConsoleOutputTemplate); - } + [Benchmark] + public void DefaultConsoleOutputTemplate() + { + _parser.Parse(_DefaultConsoleOutputTemplate); } } diff --git a/test/Serilog.PerformanceTests/MessageTemplateRenderingBenchmark.cs b/test/Serilog.PerformanceTests/MessageTemplateRenderingBenchmark.cs index a3bec8bde..bb4138119 100644 --- a/test/Serilog.PerformanceTests/MessageTemplateRenderingBenchmark.cs +++ b/test/Serilog.PerformanceTests/MessageTemplateRenderingBenchmark.cs @@ -2,32 +2,32 @@ using Serilog.Events; using Serilog.PerformanceTests.Support; -namespace Serilog.PerformanceTests +namespace Serilog.PerformanceTests; + +/// +/// Determines the cost of rendering a message template. +/// +[MemoryDiagnoser] +public class MessageTemplateRenderingBenchmark { - /// - /// Determines the cost of rendering a message template. - /// - public class MessageTemplateRenderingBenchmark - { - static readonly LogEvent NoProperties = - Some.InformationEvent("This template has no properties"); + static readonly LogEvent NoProperties = + Some.InformationEvent("This template has no properties"); - static readonly LogEvent VariedProperties = - Some.InformationEvent("Processed {@Position} for {Task} in {Elapsed:000} ms", - new { Latitude = 25, Longitude = 134 }, "Benchmark", 34); + static readonly LogEvent VariedProperties = + Some.InformationEvent("Processed {@Position} for {Task} in {Elapsed:000} ms", + new { Latitude = 25, Longitude = 134 }, "Benchmark", 34); - readonly NullTextWriter _output = new(); + readonly NullTextWriter _output = new(); - [Benchmark] - public void TemplateWithNoProperties() - { - NoProperties.MessageTemplate.Render(NoProperties.Properties, _output); - } + [Benchmark] + public void TemplateWithNoProperties() + { + NoProperties.MessageTemplate.Render(NoProperties.Properties, _output); + } - [Benchmark] - public void TemplateWithVariedProperties() - { - VariedProperties.MessageTemplate.Render(VariedProperties.Properties, _output); - } + [Benchmark] + public void TemplateWithVariedProperties() + { + VariedProperties.MessageTemplate.Render(VariedProperties.Properties, _output); } } diff --git a/test/Serilog.PerformanceTests/NestedLoggerCreationBenchmark.cs b/test/Serilog.PerformanceTests/NestedLoggerCreationBenchmark.cs index 7b7a80ead..5a22d2657 100644 --- a/test/Serilog.PerformanceTests/NestedLoggerCreationBenchmark.cs +++ b/test/Serilog.PerformanceTests/NestedLoggerCreationBenchmark.cs @@ -1,40 +1,39 @@ using BenchmarkDotNet.Attributes; using Serilog.PerformanceTests.Support; -namespace Serilog.PerformanceTests +namespace Serilog.PerformanceTests; + +/// +/// Tests the cost creating a nested logger. +/// +[MemoryDiagnoser] +public class NestedLoggerCreationBenchmark { - /// - /// Tests the cost creating a nested logger. - /// - [MemoryDiagnoser] - public class NestedLoggerCreationBenchmark - { - ILogger log = null!; + ILogger log = null!; - [GlobalSetup] - public void Setup() - { - log = new LoggerConfiguration() - .WriteTo.Sink(new NullSink()) - .CreateLogger(); - } + [GlobalSetup] + public void Setup() + { + log = new LoggerConfiguration() + .WriteTo.Sink(new NullSink()) + .CreateLogger(); + } - [Benchmark] - public void ForContextInt() - { - log.ForContext("Number", 1); - } + [Benchmark] + public void ForContextInt() + { + log.ForContext("Number", 1); + } - [Benchmark] - public void ForContextString() - { - log.ForContext("SourceContext", "Serilog.PerformanceTests"); - } + [Benchmark] + public void ForContextString() + { + log.ForContext("SourceContext", "Serilog.PerformanceTests"); + } - [Benchmark] - public void ForContextType() - { - log.ForContext(); - } + [Benchmark] + public void ForContextType() + { + log.ForContext(); } } diff --git a/test/Serilog.PerformanceTests/NestedLoggerLatencyBenchmark.cs b/test/Serilog.PerformanceTests/NestedLoggerLatencyBenchmark.cs index 9e2121db8..890642cc7 100644 --- a/test/Serilog.PerformanceTests/NestedLoggerLatencyBenchmark.cs +++ b/test/Serilog.PerformanceTests/NestedLoggerLatencyBenchmark.cs @@ -2,36 +2,35 @@ using Serilog.Events; using Serilog.PerformanceTests.Support; -namespace Serilog.PerformanceTests +namespace Serilog.PerformanceTests; + +/// +/// Tests the overhead of writing through a nested logger. +/// +public class NestedLoggerLatencyBenchmark { - /// - /// Tests the overhead of writing through a nested logger. - /// - public class NestedLoggerLatencyBenchmark - { - ILogger _log = null!, _nested = null!; - readonly LogEvent _event = Some.InformationEvent(); + ILogger _log = null!, _nested = null!; + readonly LogEvent _event = Some.InformationEvent(); - [GlobalSetup] - public void Setup() - { - _log = new LoggerConfiguration() - .WriteTo.Sink(new NullSink()) - .CreateLogger(); + [GlobalSetup] + public void Setup() + { + _log = new LoggerConfiguration() + .WriteTo.Sink(new NullSink()) + .CreateLogger(); - _nested = _log.ForContext(); - } + _nested = _log.ForContext(); + } - [Benchmark(Baseline = true)] - public void RootLogger() - { - _log.Write(_event); - } + [Benchmark(Baseline = true)] + public void RootLogger() + { + _log.Write(_event); + } - [Benchmark] - public void NestedLogger() - { - _nested.Write(_event); - } + [Benchmark] + public void NestedLogger() + { + _nested.Write(_event); } } diff --git a/test/Serilog.PerformanceTests/OutputTemplateRenderingBenchmark.cs b/test/Serilog.PerformanceTests/OutputTemplateRenderingBenchmark.cs index a0c8ecd44..a630824b0 100644 --- a/test/Serilog.PerformanceTests/OutputTemplateRenderingBenchmark.cs +++ b/test/Serilog.PerformanceTests/OutputTemplateRenderingBenchmark.cs @@ -4,24 +4,24 @@ using Serilog.Formatting.Display; using Serilog.PerformanceTests.Support; -namespace Serilog.PerformanceTests +namespace Serilog.PerformanceTests; + +/// +/// Determines the cost of rendering an event out to one of the typical text targets, +/// like the console or a text file. +/// +[MemoryDiagnoser] +public class OutputTemplateRenderingBenchmark { - /// - /// Determines the cost of rendering an event out to one of the typical text targets, - /// like the console or a text file. - /// - public class OutputTemplateRenderingBenchmark - { - const string DefaultFileOutputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}"; - static readonly LogEvent HelloWorldEvent = Some.InformationEvent("Hello, {Name}", "World"); - static readonly MessageTemplateTextFormatter Formatter = new(DefaultFileOutputTemplate, CultureInfo.InvariantCulture); + const string DefaultFileOutputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}"; + static readonly LogEvent HelloWorldEvent = Some.InformationEvent("Hello, {Name}", "World"); + static readonly MessageTemplateTextFormatter Formatter = new(DefaultFileOutputTemplate, CultureInfo.InvariantCulture); - readonly NullTextWriter _output = new(); + readonly NullTextWriter _output = new(); - [Benchmark] - public void FormatToOutput() - { - Formatter.Format(HelloWorldEvent, _output); - } + [Benchmark] + public void FormatToOutput() + { + Formatter.Format(HelloWorldEvent, _output); } } diff --git a/test/Serilog.PerformanceTests/PipelineBenchmark.cs b/test/Serilog.PerformanceTests/PipelineBenchmark.cs index 98afd8052..568ac29c8 100644 --- a/test/Serilog.PerformanceTests/PipelineBenchmark.cs +++ b/test/Serilog.PerformanceTests/PipelineBenchmark.cs @@ -16,32 +16,32 @@ using System; using Serilog.PerformanceTests.Support; -namespace Serilog.PerformanceTests +namespace Serilog.PerformanceTests; + +/// +/// Tests the cost of writing through the logging pipeline. +/// +[MemoryDiagnoser] +public class PipelineBenchmark { - /// - /// Tests the cost of writing through the logging pipeline. - /// - public class PipelineBenchmark - { - ILogger _log = null!; - Exception _exception = null!; + ILogger _log = null!; + Exception _exception = null!; - [GlobalSetup] - public void Setup() - { - _exception = new Exception("An Error"); - _log = new LoggerConfiguration() - .WriteTo.Sink(new NullSink()) - .CreateLogger(); + [GlobalSetup] + public void Setup() + { + _exception = new Exception("An Error"); + _log = new LoggerConfiguration() + .WriteTo.Sink(new NullSink()) + .CreateLogger(); - // Ensure template is cached - _log.Information(_exception, "Hello, {Name}!", "World"); - } + // Ensure template is cached + _log.Information(_exception, "Hello, {Name}!", "World"); + } - [Benchmark] - public void EmitLogEvent() - { - _log.Information(_exception, "Hello, {Name}!", "World"); - } + [Benchmark] + public void EmitLogEvent() + { + _log.Information(_exception, "Hello, {Name}!", "World"); } } diff --git a/test/Serilog.PerformanceTests/SourceContextMatchBenchmark.cs b/test/Serilog.PerformanceTests/SourceContextMatchBenchmark.cs index cedd9207f..05ef90220 100644 --- a/test/Serilog.PerformanceTests/SourceContextMatchBenchmark.cs +++ b/test/Serilog.PerformanceTests/SourceContextMatchBenchmark.cs @@ -8,88 +8,87 @@ using Serilog.Filters; using Serilog.PerformanceTests.Support; -namespace Serilog.PerformanceTests +namespace Serilog.PerformanceTests; + +[SimpleJob(RuntimeMoniker.NetCoreApp21, baseline: true)] +[SimpleJob(RuntimeMoniker.NetCoreApp31)] +public class SourceContextMatchBenchmark { - [SimpleJob(RuntimeMoniker.NetCoreApp21, baseline: true)] - [SimpleJob(RuntimeMoniker.NetCoreApp31)] - public class SourceContextMatchBenchmark + readonly LevelOverrideMap _levelOverrideMap; + readonly Logger _loggerWithOverrides; + readonly List _loggersWithFilters = new(); + readonly LogEvent _event = Some.InformationEvent(); + readonly string[] _contexts; + + public SourceContextMatchBenchmark() { - readonly LevelOverrideMap _levelOverrideMap; - readonly Logger _loggerWithOverrides; - readonly List _loggersWithFilters = new(); - readonly LogEvent _event = Some.InformationEvent(); - readonly string[] _contexts; + _contexts = new[] + { + "Serilog", + "MyApp", + "MyAppSomething", + "MyOtherApp", + "MyApp.Something", + "MyApp.Api.Models.Person", + "MyApp.Api.Controllers.AboutController", + "MyApp.Api.Controllers.HomeController", + "Api.Controllers.HomeController" + }; - public SourceContextMatchBenchmark() + var overrides = new Dictionary { - _contexts = new[] - { - "Serilog", - "MyApp", - "MyAppSomething", - "MyOtherApp", - "MyApp.Something", - "MyApp.Api.Models.Person", - "MyApp.Api.Controllers.AboutController", - "MyApp.Api.Controllers.HomeController", - "Api.Controllers.HomeController" - }; + ["MyApp"] = new(LogEventLevel.Debug), + ["MyApp.Api.Controllers"] = new(LogEventLevel.Information), + ["MyApp.Api.Controllers.HomeController"] = new(LogEventLevel.Warning), + ["MyApp.Api"] = new(LogEventLevel.Error) + }; - var overrides = new Dictionary - { - ["MyApp"] = new(LogEventLevel.Debug), - ["MyApp.Api.Controllers"] = new(LogEventLevel.Information), - ["MyApp.Api.Controllers.HomeController"] = new(LogEventLevel.Warning), - ["MyApp.Api"] = new(LogEventLevel.Error) - }; + _levelOverrideMap = new(overrides, LogEventLevel.Fatal, null); - _levelOverrideMap = new(overrides, LogEventLevel.Fatal, null); + var loggerConfiguration = new LoggerConfiguration().MinimumLevel.Fatal(); - var loggerConfiguration = new LoggerConfiguration().MinimumLevel.Fatal(); + foreach (var @override in overrides) + { + loggerConfiguration = loggerConfiguration.MinimumLevel.Override(@override.Key, @override.Value); - foreach (var @override in overrides) + foreach (var ctx in _contexts) { - loggerConfiguration = loggerConfiguration.MinimumLevel.Override(@override.Key, @override.Value); - - foreach (var ctx in _contexts) - { - _loggersWithFilters.Add( - new LoggerConfiguration().MinimumLevel.Verbose() - .Filter.ByIncludingOnly(Matching.FromSource(@override.Key)) - .WriteTo.Sink() - .CreateLogger() - .ForContext(Constants.SourceContextPropertyName, ctx)); - } + _loggersWithFilters.Add( + new LoggerConfiguration().MinimumLevel.Verbose() + .Filter.ByIncludingOnly(Matching.FromSource(@override.Key)) + .WriteTo.Sink() + .CreateLogger() + .ForContext(Constants.SourceContextPropertyName, ctx)); } - - _loggerWithOverrides = loggerConfiguration.WriteTo.Sink().CreateLogger(); } - [Benchmark] - public void Filter_MatchingFromSource() + _loggerWithOverrides = loggerConfiguration.WriteTo.Sink().CreateLogger(); + } + + [Benchmark] + public void Filter_MatchingFromSource() + { + for (var i = 0; i < _loggersWithFilters.Count; ++i) { - for (var i = 0; i < _loggersWithFilters.Count; ++i) - { - _loggersWithFilters[i].Write(_event); - } + _loggersWithFilters[i].Write(_event); } + } - [Benchmark] - public void Logger_ForContext() + [Benchmark] + public void Logger_ForContext() + { + for (var i = 0; i < _contexts.Length; ++i) { - for (var i = 0; i < _contexts.Length; ++i) - { - _loggerWithOverrides.ForContext(Constants.SourceContextPropertyName, _contexts[i]); - } + _loggerWithOverrides.ForContext(Constants.SourceContextPropertyName, _contexts[i]); } + } - [Benchmark] - public void LevelOverrideMap_GetEffectiveLevel() + [Benchmark] + public void LevelOverrideMap_GetEffectiveLevel() + { + for (var i = 0; i < _contexts.Length; ++i) { - for (var i = 0; i < _contexts.Length; ++i) - { - _levelOverrideMap.GetEffectiveLevel(_contexts[i], out _, out _); - } + _levelOverrideMap.GetEffectiveLevel(_contexts[i], out _, out _); } } } diff --git a/test/Serilog.PerformanceTests/Support/ConcurrentDictionaryTemplateCache.cs b/test/Serilog.PerformanceTests/Support/ConcurrentDictionaryTemplateCache.cs index 70a85fbe5..28c74236f 100644 --- a/test/Serilog.PerformanceTests/Support/ConcurrentDictionaryTemplateCache.cs +++ b/test/Serilog.PerformanceTests/Support/ConcurrentDictionaryTemplateCache.cs @@ -1,52 +1,51 @@ -using System; +using System; using System.Collections.Concurrent; using Serilog.Core; using Serilog.Events; -namespace Serilog.PerformanceTests.Support +namespace Serilog.PerformanceTests.Support; + +class ConcurrentDictionaryMessageTemplateCache : IMessageTemplateParser { - class ConcurrentDictionaryMessageTemplateCache : IMessageTemplateParser - { - readonly IMessageTemplateParser _innerParser; + readonly IMessageTemplateParser _innerParser; - readonly ConcurrentDictionary _templates = new(); + readonly ConcurrentDictionary _templates = new(); - const int MaxCacheItems = 1000; - const int MaxCachedTemplateLength = 1024; + const int MaxCacheItems = 1000; + const int MaxCachedTemplateLength = 1024; - public ConcurrentDictionaryMessageTemplateCache(IMessageTemplateParser innerParser) - { - _innerParser = innerParser ?? throw new ArgumentNullException(nameof(innerParser)); - } - - public MessageTemplate Parse(string messageTemplate) - { - if (messageTemplate == null) throw new ArgumentNullException(nameof(messageTemplate)); + public ConcurrentDictionaryMessageTemplateCache(IMessageTemplateParser innerParser) + { + _innerParser = innerParser ?? throw new ArgumentNullException(nameof(innerParser)); + } - if (messageTemplate.Length > MaxCachedTemplateLength) - return _innerParser.Parse(messageTemplate); + public MessageTemplate Parse(string messageTemplate) + { + if (messageTemplate == null) throw new ArgumentNullException(nameof(messageTemplate)); - if (_templates.TryGetValue(messageTemplate, out var result)) - return result; + if (messageTemplate.Length > MaxCachedTemplateLength) + return _innerParser.Parse(messageTemplate); - result = _innerParser.Parse(messageTemplate); + if (_templates.TryGetValue(messageTemplate, out var result)) + return result; - { - // Exceeding MaxCacheItems is *not* the sunny day scenario; all we're doing here is preventing out-of-memory - // conditions when the library is used incorrectly. Correct use (templates, rather than - // direct message strings) should barely, if ever, overflow this cache. + result = _innerParser.Parse(messageTemplate); - // Changing workloads through the lifecycle of an app instance mean we can gain some ground by - // potentially dropping templates generated only in startup, or only during specific infrequent - // activities. + { + // Exceeding MaxCacheItems is *not* the sunny day scenario; all we're doing here is preventing out-of-memory + // conditions when the library is used incorrectly. Correct use (templates, rather than + // direct message strings) should barely, if ever, overflow this cache. - if (_templates.Count == MaxCacheItems) - _templates.Clear(); + // Changing workloads through the lifecycle of an app instance mean we can gain some ground by + // potentially dropping templates generated only in startup, or only during specific infrequent + // activities. - _templates[messageTemplate] = result; - } + if (_templates.Count == MaxCacheItems) + _templates.Clear(); - return result; + _templates[messageTemplate] = result; } + + return result; } } diff --git a/test/Serilog.PerformanceTests/Support/DictionaryMessageTemplateCache.cs b/test/Serilog.PerformanceTests/Support/DictionaryMessageTemplateCache.cs index 78f80c354..f6dcf5457 100644 --- a/test/Serilog.PerformanceTests/Support/DictionaryMessageTemplateCache.cs +++ b/test/Serilog.PerformanceTests/Support/DictionaryMessageTemplateCache.cs @@ -3,54 +3,53 @@ using Serilog.Core; using Serilog.Events; -namespace Serilog.PerformanceTests.Support -{ - class DictionaryMessageTemplateCache : IMessageTemplateParser - { - readonly IMessageTemplateParser _innerParser; - readonly object _templatesLock = new(); +namespace Serilog.PerformanceTests.Support; - readonly Dictionary _templates = new(); +class DictionaryMessageTemplateCache : IMessageTemplateParser +{ + readonly IMessageTemplateParser _innerParser; + readonly object _templatesLock = new(); - const int MaxCacheItems = 1000; - const int MaxCachedTemplateLength = 1024; + readonly Dictionary _templates = new(); - public DictionaryMessageTemplateCache(IMessageTemplateParser innerParser) - { - _innerParser = innerParser ?? throw new ArgumentNullException(nameof(innerParser)); - } + const int MaxCacheItems = 1000; + const int MaxCachedTemplateLength = 1024; - public MessageTemplate Parse(string messageTemplate) - { - if (messageTemplate == null) throw new ArgumentNullException(nameof(messageTemplate)); + public DictionaryMessageTemplateCache(IMessageTemplateParser innerParser) + { + _innerParser = innerParser ?? throw new ArgumentNullException(nameof(innerParser)); + } - if (messageTemplate.Length > MaxCachedTemplateLength) - return _innerParser.Parse(messageTemplate); + public MessageTemplate Parse(string messageTemplate) + { + if (messageTemplate == null) throw new ArgumentNullException(nameof(messageTemplate)); - MessageTemplate? result; - lock (_templatesLock) - if (_templates.TryGetValue(messageTemplate, out result)) - return result; + if (messageTemplate.Length > MaxCachedTemplateLength) + return _innerParser.Parse(messageTemplate); - result = _innerParser.Parse(messageTemplate); + MessageTemplate? result; + lock (_templatesLock) + if (_templates.TryGetValue(messageTemplate, out result)) + return result; - lock (_templatesLock) - { - // Exceeding MaxCacheItems is *not* the sunny day scenario; all we're doing here is preventing out-of-memory - // conditions when the library is used incorrectly. Correct use (templates, rather than - // direct message strings) should barely, if ever, overflow this cache. + result = _innerParser.Parse(messageTemplate); - // Changing workloads through the lifecycle of an app instance mean we can gain some ground by - // potentially dropping templates generated only in startup, or only during specific infrequent - // activities. + lock (_templatesLock) + { + // Exceeding MaxCacheItems is *not* the sunny day scenario; all we're doing here is preventing out-of-memory + // conditions when the library is used incorrectly. Correct use (templates, rather than + // direct message strings) should barely, if ever, overflow this cache. - if (_templates.Count == MaxCacheItems) - _templates.Clear(); + // Changing workloads through the lifecycle of an app instance mean we can gain some ground by + // potentially dropping templates generated only in startup, or only during specific infrequent + // activities. - _templates[messageTemplate] = result; - } + if (_templates.Count == MaxCacheItems) + _templates.Clear(); - return result; + _templates[messageTemplate] = result; } + + return result; } } diff --git a/test/Serilog.PerformanceTests/Support/NoOpMessageTemplateParser.cs b/test/Serilog.PerformanceTests/Support/NoOpMessageTemplateParser.cs index 7f68de2a5..8cf1d2750 100644 --- a/test/Serilog.PerformanceTests/Support/NoOpMessageTemplateParser.cs +++ b/test/Serilog.PerformanceTests/Support/NoOpMessageTemplateParser.cs @@ -1,16 +1,15 @@ -using System.Linq; +using System.Linq; using Serilog.Core; using Serilog.Events; using Serilog.Parsing; -namespace Serilog.PerformanceTests.Support +namespace Serilog.PerformanceTests.Support; + +class NoOpMessageTemplateParser : IMessageTemplateParser { - class NoOpMessageTemplateParser : IMessageTemplateParser - { - public static readonly NoOpMessageTemplateParser Instance = new(); + public static readonly NoOpMessageTemplateParser Instance = new(); - static readonly MessageTemplate ConstTemplate = new("text", Enumerable.Empty()); + static readonly MessageTemplate ConstTemplate = new("text", Enumerable.Empty()); - public MessageTemplate Parse(string messageTemplate) => ConstTemplate; - } -} \ No newline at end of file + public MessageTemplate Parse(string messageTemplate) => ConstTemplate; +} diff --git a/test/Serilog.PerformanceTests/Support/NullSink.cs b/test/Serilog.PerformanceTests/Support/NullSink.cs index 99426a4df..c063d684a 100644 --- a/test/Serilog.PerformanceTests/Support/NullSink.cs +++ b/test/Serilog.PerformanceTests/Support/NullSink.cs @@ -1,12 +1,11 @@ -using Serilog.Core; +using Serilog.Core; using Serilog.Events; -namespace Serilog.PerformanceTests.Support +namespace Serilog.PerformanceTests.Support; + +class NullSink : ILogEventSink { - class NullSink : ILogEventSink + public void Emit(LogEvent logEvent) { - public void Emit(LogEvent logEvent) - { - } } } diff --git a/test/Serilog.PerformanceTests/Support/NullTextWriter.cs b/test/Serilog.PerformanceTests/Support/NullTextWriter.cs index 24e459ebb..50912ca7b 100644 --- a/test/Serilog.PerformanceTests/Support/NullTextWriter.cs +++ b/test/Serilog.PerformanceTests/Support/NullTextWriter.cs @@ -1,156 +1,155 @@ using System.IO; using System.Text; -namespace Serilog.PerformanceTests.Support +namespace Serilog.PerformanceTests.Support; + +class NullTextWriter : TextWriter { - class NullTextWriter : TextWriter + public override void Write(char value) { - public override void Write(char value) - { - } + } - public override Encoding Encoding { get; } = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); + public override Encoding Encoding { get; } = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); - public override void Write(bool value) - { - } + public override void Write(bool value) + { + } - public override void Write(char[]? buffer) - { - } + public override void Write(char[]? buffer) + { + } - public override void Write(char[] buffer, int index, int count) - { - } + public override void Write(char[] buffer, int index, int count) + { + } - public override void Write(decimal value) - { - } + public override void Write(decimal value) + { + } - public override void Write(double value) - { - } + public override void Write(double value) + { + } - public override void Write(int value) - { - } + public override void Write(int value) + { + } - public override void Write(long value) - { - } + public override void Write(long value) + { + } - public override void Write(object? value) - { - } + public override void Write(object? value) + { + } - public override void Write(float value) - { - } + public override void Write(float value) + { + } - public override void Write(string? value) - { - } + public override void Write(string? value) + { + } - public override void Write(string format, object? arg0) - { - } + public override void Write(string format, object? arg0) + { + } - public override void Write(string format, object? arg0, object? arg1) - { - } + public override void Write(string format, object? arg0, object? arg1) + { + } - public override void Write(string format, object? arg0, object? arg1, object? arg2) - { - } + public override void Write(string format, object? arg0, object? arg1, object? arg2) + { + } - public override void Write(string format, params object?[] arg) - { - } + public override void Write(string format, params object?[] arg) + { + } - public override void Write(uint value) - { - } + public override void Write(uint value) + { + } - public override void Write(ulong value) - { - } + public override void Write(ulong value) + { + } - public override string ToString() => string.Empty; + public override string ToString() => string.Empty; - public override void Flush() - { - } + public override void Flush() + { + } - public override void WriteLine() - { - } + public override void WriteLine() + { + } - public override void WriteLine(bool value) - { - } + public override void WriteLine(bool value) + { + } - public override void WriteLine(char value) - { - } + public override void WriteLine(char value) + { + } - public override void WriteLine(char[]? buffer) - { - } + public override void WriteLine(char[]? buffer) + { + } - public override void WriteLine(char[] buffer, int index, int count) - { - } + public override void WriteLine(char[] buffer, int index, int count) + { + } - public override void WriteLine(decimal value) - { - } + public override void WriteLine(decimal value) + { + } - public override void WriteLine(double value) - { - } + public override void WriteLine(double value) + { + } - public override void WriteLine(int value) - { - } + public override void WriteLine(int value) + { + } - public override void WriteLine(long value) - { - } + public override void WriteLine(long value) + { + } - public override void WriteLine(object? value) - { - } + public override void WriteLine(object? value) + { + } - public override void WriteLine(float value) - { - } + public override void WriteLine(float value) + { + } - public override void WriteLine(string? value) - { - } + public override void WriteLine(string? value) + { + } - public override void WriteLine(string format, object? arg0) - { - } + public override void WriteLine(string format, object? arg0) + { + } - public override void WriteLine(string format, object? arg0, object? arg1) - { - } + public override void WriteLine(string format, object? arg0, object? arg1) + { + } - public override void WriteLine(string format, object? arg0, object? arg1, object? arg2) - { - } + public override void WriteLine(string format, object? arg0, object? arg1, object? arg2) + { + } - public override void WriteLine(string format, params object?[] arg) - { - } + public override void WriteLine(string format, params object?[] arg) + { + } - public override void WriteLine(uint value) - { - } + public override void WriteLine(uint value) + { + } - public override void WriteLine(ulong value) - { - } + public override void WriteLine(ulong value) + { } } diff --git a/test/Serilog.PerformanceTests/Support/Some.cs b/test/Serilog.PerformanceTests/Support/Some.cs index 91a7eac33..fb63381f2 100644 --- a/test/Serilog.PerformanceTests/Support/Some.cs +++ b/test/Serilog.PerformanceTests/Support/Some.cs @@ -1,17 +1,16 @@ using System; using Serilog.Events; -namespace Serilog.PerformanceTests.Support +namespace Serilog.PerformanceTests.Support; + +static class Some { - static class Some + public static LogEvent InformationEvent(string messageTemplate = "Hello, world!", params object[] propertyValues) { - public static LogEvent InformationEvent(string messageTemplate = "Hello, world!", params object[] propertyValues) - { - var logger = new LoggerConfiguration().CreateLogger(); + var logger = new LoggerConfiguration().CreateLogger(); #pragma warning disable Serilog004 // Constant MessageTemplate verifier - logger.BindMessageTemplate(messageTemplate, propertyValues, out var parsedTemplate, out var boundProperties); + logger.BindMessageTemplate(messageTemplate, propertyValues, out var parsedTemplate, out var boundProperties); #pragma warning restore Serilog004 // Constant MessageTemplate verifier - return new LogEvent(DateTime.Now, LogEventLevel.Information, null, parsedTemplate!, boundProperties!); - } + return new LogEvent(DateTime.Now, LogEventLevel.Information, null, parsedTemplate!, boundProperties!); } } diff --git a/test/TestDummies/Console/DummyConsoleSink.cs b/test/TestDummies/Console/DummyConsoleSink.cs index ab8e5ba9e..7d942bb05 100644 --- a/test/TestDummies/Console/DummyConsoleSink.cs +++ b/test/TestDummies/Console/DummyConsoleSink.cs @@ -3,20 +3,19 @@ using Serilog.Events; using TestDummies.Console.Themes; -namespace TestDummies.Console +namespace TestDummies.Console; + +public class DummyConsoleSink : ILogEventSink { - public class DummyConsoleSink : ILogEventSink + public DummyConsoleSink(ConsoleTheme? theme = null) { - public DummyConsoleSink(ConsoleTheme? theme = null) - { - Theme = theme ?? ConsoleTheme.None; - } + Theme = theme ?? ConsoleTheme.None; + } - [ThreadStatic] - public static ConsoleTheme? Theme; + [ThreadStatic] + public static ConsoleTheme? Theme; - public void Emit(LogEvent logEvent) - { - } + public void Emit(LogEvent logEvent) + { } } diff --git a/test/TestDummies/Console/Themes/ConcreteConsoleTheme.cs b/test/TestDummies/Console/Themes/ConcreteConsoleTheme.cs index 8b3b041b2..67d8343e4 100644 --- a/test/TestDummies/Console/Themes/ConcreteConsoleTheme.cs +++ b/test/TestDummies/Console/Themes/ConcreteConsoleTheme.cs @@ -1,6 +1,5 @@ -namespace TestDummies.Console.Themes +namespace TestDummies.Console.Themes; + +class ConcreteConsoleTheme : ConsoleTheme { - class ConcreteConsoleTheme : ConsoleTheme - { - } } diff --git a/test/TestDummies/Console/Themes/ConsoleTheme.cs b/test/TestDummies/Console/Themes/ConsoleTheme.cs index 1c5aaf5da..ff14007ba 100644 --- a/test/TestDummies/Console/Themes/ConsoleTheme.cs +++ b/test/TestDummies/Console/Themes/ConsoleTheme.cs @@ -1,7 +1,6 @@ -namespace TestDummies.Console.Themes +namespace TestDummies.Console.Themes; + +public abstract class ConsoleTheme { - public abstract class ConsoleTheme - { - public static ConsoleTheme None { get; } = new EmptyConsoleTheme(); - } + public static ConsoleTheme None { get; } = new EmptyConsoleTheme(); } diff --git a/test/TestDummies/Console/Themes/ConsoleThemes.cs b/test/TestDummies/Console/Themes/ConsoleThemes.cs index 7bb414cb8..2804ba711 100644 --- a/test/TestDummies/Console/Themes/ConsoleThemes.cs +++ b/test/TestDummies/Console/Themes/ConsoleThemes.cs @@ -1,7 +1,6 @@ -namespace TestDummies.Console.Themes +namespace TestDummies.Console.Themes; + +public static class ConsoleThemes { - public static class ConsoleThemes - { - public static ConsoleTheme Theme1 { get; } = new ConcreteConsoleTheme(); - } + public static ConsoleTheme Theme1 { get; } = new ConcreteConsoleTheme(); } diff --git a/test/TestDummies/Console/Themes/EmptyConsoleTheme.cs b/test/TestDummies/Console/Themes/EmptyConsoleTheme.cs index 100e89e87..f01847f85 100644 --- a/test/TestDummies/Console/Themes/EmptyConsoleTheme.cs +++ b/test/TestDummies/Console/Themes/EmptyConsoleTheme.cs @@ -1,6 +1,5 @@ -namespace TestDummies.Console.Themes +namespace TestDummies.Console.Themes; + +class EmptyConsoleTheme : ConsoleTheme { - class EmptyConsoleTheme : ConsoleTheme - { - } } diff --git a/test/TestDummies/DummyAnonymousUserFilter.cs b/test/TestDummies/DummyAnonymousUserFilter.cs index 9d2f1291d..222d07d70 100644 --- a/test/TestDummies/DummyAnonymousUserFilter.cs +++ b/test/TestDummies/DummyAnonymousUserFilter.cs @@ -1,24 +1,23 @@ -using Serilog.Core; +using Serilog.Core; using Serilog.Events; -namespace TestDummies +namespace TestDummies; + +public class DummyAnonymousUserFilter : ILogEventFilter { - public class DummyAnonymousUserFilter : ILogEventFilter + public bool IsEnabled(LogEvent logEvent) { - public bool IsEnabled(LogEvent logEvent) + if (logEvent.Properties.ContainsKey("User")) { - if (logEvent.Properties.ContainsKey("User")) + if (logEvent.Properties["User"] is ScalarValue sv) { - if (logEvent.Properties["User"] is ScalarValue sv) + if (sv.Value is string s && s == "anonymous") { - if (sv.Value is string s && s == "anonymous") - { - return false; - } + return false; } } - - return true; } + + return true; } } diff --git a/test/TestDummies/DummyHardCodedStringDestructuringPolicy.cs b/test/TestDummies/DummyHardCodedStringDestructuringPolicy.cs index 25d272490..1b85d713f 100644 --- a/test/TestDummies/DummyHardCodedStringDestructuringPolicy.cs +++ b/test/TestDummies/DummyHardCodedStringDestructuringPolicy.cs @@ -1,22 +1,21 @@ -using System; +using System; using Serilog.Core; using Serilog.Events; -namespace TestDummies +namespace TestDummies; + +public class DummyHardCodedStringDestructuringPolicy : IDestructuringPolicy { - public class DummyHardCodedStringDestructuringPolicy : IDestructuringPolicy - { - readonly string _hardCodedString; + readonly string _hardCodedString; - public DummyHardCodedStringDestructuringPolicy(string hardCodedString) - { - _hardCodedString = hardCodedString ?? throw new ArgumentNullException(nameof(hardCodedString)); - } + public DummyHardCodedStringDestructuringPolicy(string hardCodedString) + { + _hardCodedString = hardCodedString ?? throw new ArgumentNullException(nameof(hardCodedString)); + } - public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyValueFactory, out LogEventPropertyValue result) - { - result = new ScalarValue(_hardCodedString); - return true; - } + public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyValueFactory, out LogEventPropertyValue result) + { + result = new ScalarValue(_hardCodedString); + return true; } } diff --git a/test/TestDummies/DummyLoggerConfigurationExtensions.cs b/test/TestDummies/DummyLoggerConfigurationExtensions.cs index 123a8aa0a..6f65754d5 100644 --- a/test/TestDummies/DummyLoggerConfigurationExtensions.cs +++ b/test/TestDummies/DummyLoggerConfigurationExtensions.cs @@ -7,88 +7,87 @@ using TestDummies.Console; using TestDummies.Console.Themes; -namespace TestDummies +namespace TestDummies; + +public static class DummyLoggerConfigurationExtensions { - public static class DummyLoggerConfigurationExtensions + public static LoggerConfiguration WithDummyThreadId(this LoggerEnrichmentConfiguration enrich) { - public static LoggerConfiguration WithDummyThreadId(this LoggerEnrichmentConfiguration enrich) - { - return enrich.With(new DummyThreadIdEnricher()); - } + return enrich.With(new DummyThreadIdEnricher()); + } - public static LoggerConfiguration DummyRollingFile( - this LoggerSinkConfiguration loggerSinkConfiguration, - string pathFormat, - LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, - string? outputTemplate = null, - IFormatProvider? formatProvider = null) - { - return loggerSinkConfiguration.Sink(new DummyRollingFileSink(), restrictedToMinimumLevel); - } + public static LoggerConfiguration DummyRollingFile( + this LoggerSinkConfiguration loggerSinkConfiguration, + string pathFormat, + LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, + string? outputTemplate = null, + IFormatProvider? formatProvider = null) + { + return loggerSinkConfiguration.Sink(new DummyRollingFileSink(), restrictedToMinimumLevel); + } - public static LoggerConfiguration DummyRollingFile( - this LoggerSinkConfiguration loggerSinkConfiguration, - ITextFormatter formatter, - string pathFormat, - LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum) - { - return loggerSinkConfiguration.Sink(new DummyRollingFileSink(), restrictedToMinimumLevel); - } + public static LoggerConfiguration DummyRollingFile( + this LoggerSinkConfiguration loggerSinkConfiguration, + ITextFormatter formatter, + string pathFormat, + LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum) + { + return loggerSinkConfiguration.Sink(new DummyRollingFileSink(), restrictedToMinimumLevel); + } - public static LoggerConfiguration DummyRollingFile( - this LoggerAuditSinkConfiguration loggerSinkConfiguration, - LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum) - { - return loggerSinkConfiguration.Sink(new DummyRollingFileAuditSink(), restrictedToMinimumLevel); - } + public static LoggerConfiguration DummyRollingFile( + this LoggerAuditSinkConfiguration loggerSinkConfiguration, + LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum) + { + return loggerSinkConfiguration.Sink(new DummyRollingFileAuditSink(), restrictedToMinimumLevel); + } - public static LoggerConfiguration DummyWithLevelSwitch( - this LoggerSinkConfiguration loggerSinkConfiguration, - LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, - LoggingLevelSwitch? controlLevelSwitch = null) - { - return loggerSinkConfiguration.Sink(new DummyWithLevelSwitchSink(controlLevelSwitch), restrictedToMinimumLevel); - } + public static LoggerConfiguration DummyWithLevelSwitch( + this LoggerSinkConfiguration loggerSinkConfiguration, + LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, + LoggingLevelSwitch? controlLevelSwitch = null) + { + return loggerSinkConfiguration.Sink(new DummyWithLevelSwitchSink(controlLevelSwitch), restrictedToMinimumLevel); + } - public static LoggerConfiguration DummyConsole( - this LoggerSinkConfiguration loggerSinkConfiguration, - LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, - ConsoleTheme? theme = null) - { - return loggerSinkConfiguration.Sink(new DummyConsoleSink(theme), restrictedToMinimumLevel); - } + public static LoggerConfiguration DummyConsole( + this LoggerSinkConfiguration loggerSinkConfiguration, + LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, + ConsoleTheme? theme = null) + { + return loggerSinkConfiguration.Sink(new DummyConsoleSink(theme), restrictedToMinimumLevel); + } - public static LoggerConfiguration Dummy( - this LoggerSinkConfiguration loggerSinkConfiguration, - Action wrappedSinkAction) - { - return LoggerSinkConfiguration.Wrap( - loggerSinkConfiguration, - s => new DummyWrappingSink(s), - wrappedSinkAction, - LevelAlias.Minimum, - null); - } + public static LoggerConfiguration Dummy( + this LoggerSinkConfiguration loggerSinkConfiguration, + Action wrappedSinkAction) + { + return LoggerSinkConfiguration.Wrap( + loggerSinkConfiguration, + s => new DummyWrappingSink(s), + wrappedSinkAction, + LevelAlias.Minimum, + null); + } - public static LoggerConfiguration DummyWrap( - this LoggerSinkConfiguration loggerSinkConfiguration, - Action wrappedSinkAction, - LogEventLevel logEventLevel, - LoggingLevelSwitch? levelSwitch) - { - return LoggerSinkConfiguration.Wrap( - loggerSinkConfiguration, - s => new DummyWrappingSink(s), - wrappedSinkAction, - logEventLevel, - levelSwitch); - } + public static LoggerConfiguration DummyWrap( + this LoggerSinkConfiguration loggerSinkConfiguration, + Action wrappedSinkAction, + LogEventLevel logEventLevel, + LoggingLevelSwitch? levelSwitch) + { + return LoggerSinkConfiguration.Wrap( + loggerSinkConfiguration, + s => new DummyWrappingSink(s), + wrappedSinkAction, + logEventLevel, + levelSwitch); + } - public static LoggerConfiguration WithDummyHardCodedString( - this LoggerDestructuringConfiguration loggerDestructuringConfiguration, - string hardCodedString) - { - return loggerDestructuringConfiguration.With(new DummyHardCodedStringDestructuringPolicy(hardCodedString)); - } + public static LoggerConfiguration WithDummyHardCodedString( + this LoggerDestructuringConfiguration loggerDestructuringConfiguration, + string hardCodedString) + { + return loggerDestructuringConfiguration.With(new DummyHardCodedStringDestructuringPolicy(hardCodedString)); } } diff --git a/test/TestDummies/DummyReduceVersionToMajorPolicy.cs b/test/TestDummies/DummyReduceVersionToMajorPolicy.cs index 9bc5fca45..a49dc073f 100644 --- a/test/TestDummies/DummyReduceVersionToMajorPolicy.cs +++ b/test/TestDummies/DummyReduceVersionToMajorPolicy.cs @@ -3,20 +3,19 @@ using Serilog.Core; using Serilog.Events; -namespace TestDummies +namespace TestDummies; + +public class DummyReduceVersionToMajorPolicy : IDestructuringPolicy { - public class DummyReduceVersionToMajorPolicy : IDestructuringPolicy + public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyValueFactory, [NotNullWhen(true)] out LogEventPropertyValue? result) { - public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyValueFactory, [NotNullWhen(true)] out LogEventPropertyValue? result) + if (value is Version version) { - if (value is Version version) - { - result = new ScalarValue(version.Major); - return true; - } - - result = null; - return false; + result = new ScalarValue(version.Major); + return true; } + + result = null; + return false; } } diff --git a/test/TestDummies/DummyRollingFileAuditSink.cs b/test/TestDummies/DummyRollingFileAuditSink.cs index caf8460a6..d363c0815 100644 --- a/test/TestDummies/DummyRollingFileAuditSink.cs +++ b/test/TestDummies/DummyRollingFileAuditSink.cs @@ -3,23 +3,22 @@ using Serilog.Core; using Serilog.Events; -namespace TestDummies +namespace TestDummies; + +public class DummyRollingFileAuditSink : ILogEventSink { - public class DummyRollingFileAuditSink : ILogEventSink - { - [ThreadStatic] - static List? _emitted; + [ThreadStatic] + static List? _emitted; - public static List Emitted => _emitted ?? (_emitted = new()); + public static List Emitted => _emitted ?? (_emitted = new()); - public void Emit(LogEvent logEvent) - { - Emitted.Add(logEvent); - } + public void Emit(LogEvent logEvent) + { + Emitted.Add(logEvent); + } - public static void Reset() - { - _emitted = null; - } + public static void Reset() + { + _emitted = null; } } diff --git a/test/TestDummies/DummyRollingFileSink.cs b/test/TestDummies/DummyRollingFileSink.cs index cac347067..9232e733e 100644 --- a/test/TestDummies/DummyRollingFileSink.cs +++ b/test/TestDummies/DummyRollingFileSink.cs @@ -3,23 +3,22 @@ using Serilog.Core; using Serilog.Events; -namespace TestDummies +namespace TestDummies; + +public class DummyRollingFileSink : ILogEventSink { - public class DummyRollingFileSink : ILogEventSink - { - [ThreadStatic] - static List? _emitted; + [ThreadStatic] + static List? _emitted; - public static List Emitted => _emitted ?? (_emitted = new()); + public static List Emitted => _emitted ?? (_emitted = new()); - public void Emit(LogEvent logEvent) - { - Emitted.Add(logEvent); - } + public void Emit(LogEvent logEvent) + { + Emitted.Add(logEvent); + } - public static void Reset() - { - _emitted = null; - } + public static void Reset() + { + _emitted = null; } } diff --git a/test/TestDummies/DummyThreadIdEnricher.cs b/test/TestDummies/DummyThreadIdEnricher.cs index a640d55e4..1cb5fe227 100644 --- a/test/TestDummies/DummyThreadIdEnricher.cs +++ b/test/TestDummies/DummyThreadIdEnricher.cs @@ -1,14 +1,13 @@ -using Serilog.Core; +using Serilog.Core; using Serilog.Events; -namespace TestDummies +namespace TestDummies; + +public class DummyThreadIdEnricher : ILogEventEnricher { - public class DummyThreadIdEnricher : ILogEventEnricher + public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) { - public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) - { - logEvent.AddPropertyIfAbsent(propertyFactory - .CreateProperty("ThreadId", "SomeId")); - } + logEvent.AddPropertyIfAbsent(propertyFactory + .CreateProperty("ThreadId", "SomeId")); } } diff --git a/test/TestDummies/DummyWithLevelSwitchSink.cs b/test/TestDummies/DummyWithLevelSwitchSink.cs index 07c47465d..3470ec67b 100644 --- a/test/TestDummies/DummyWithLevelSwitchSink.cs +++ b/test/TestDummies/DummyWithLevelSwitchSink.cs @@ -3,26 +3,25 @@ using Serilog.Core; using Serilog.Events; -namespace TestDummies +namespace TestDummies; + +public class DummyWithLevelSwitchSink : ILogEventSink { - public class DummyWithLevelSwitchSink : ILogEventSink + public DummyWithLevelSwitchSink(LoggingLevelSwitch? loggingControlLevelSwitch) { - public DummyWithLevelSwitchSink(LoggingLevelSwitch? loggingControlLevelSwitch) - { - ControlLevelSwitch = loggingControlLevelSwitch; - } + ControlLevelSwitch = loggingControlLevelSwitch; + } - [ThreadStatic] - public static LoggingLevelSwitch? ControlLevelSwitch; + [ThreadStatic] + public static LoggingLevelSwitch? ControlLevelSwitch; - [ThreadStatic] - // ReSharper disable ThreadStaticFieldHasInitializer - public static List Emitted = new(); - // ReSharper restore ThreadStaticFieldHasInitializer + [ThreadStatic] + // ReSharper disable ThreadStaticFieldHasInitializer + public static List Emitted = new(); + // ReSharper restore ThreadStaticFieldHasInitializer - public void Emit(LogEvent logEvent) - { - Emitted.Add(logEvent); - } + public void Emit(LogEvent logEvent) + { + Emitted.Add(logEvent); } } diff --git a/test/TestDummies/DummyWrappingSink.cs b/test/TestDummies/DummyWrappingSink.cs index 71bdb383b..6241450e9 100644 --- a/test/TestDummies/DummyWrappingSink.cs +++ b/test/TestDummies/DummyWrappingSink.cs @@ -3,31 +3,30 @@ using Serilog.Events; using System.Collections.Generic; -namespace TestDummies +namespace TestDummies; + +public class DummyWrappingSink : ILogEventSink { - public class DummyWrappingSink : ILogEventSink - { - [ThreadStatic] - static List? _emitted; + [ThreadStatic] + static List? _emitted; - public static List Emitted => _emitted ?? (_emitted = new()); + public static List Emitted => _emitted ?? (_emitted = new()); - readonly ILogEventSink _sink; + readonly ILogEventSink _sink; - public DummyWrappingSink(ILogEventSink sink) - { - _sink = sink; - } + public DummyWrappingSink(ILogEventSink sink) + { + _sink = sink; + } - public void Emit(LogEvent logEvent) - { - Emitted.Add(logEvent); - _sink.Emit(logEvent); - } + public void Emit(LogEvent logEvent) + { + Emitted.Add(logEvent); + _sink.Emit(logEvent); + } - public static void Reset() - { - _emitted = null; - } + public static void Reset() + { + _emitted = null; } }