diff --git a/.editorconfig b/.editorconfig index 36f9632c..ed882c8b 100644 --- a/.editorconfig +++ b/.editorconfig @@ -14,4 +14,12 @@ trim_trailing_whitespace = true # .NET formatting rules [*.{cs,vb}] -dotnet_sort_system_directives_first = true \ No newline at end of file +dotnet_sort_system_directives_first = true + +[test/**/*.cs] +# CA1873: Avoid potentially expensive logging +dotnet_diagnostic.CA1873.severity = none +# CA2253: Named placeholders should not be numeric values +dotnet_diagnostic.CA2253.severity = none +# CA2254: Template should be a static expression +dotnet_diagnostic.CA2254.severity = none \ No newline at end of file diff --git a/test/NLog.Extensions.Hosting.Tests/ExtensionMethodTests.cs b/test/NLog.Extensions.Hosting.Tests/ExtensionMethodTests.cs index 69923c33..792a2572 100644 --- a/test/NLog.Extensions.Hosting.Tests/ExtensionMethodTests.cs +++ b/test/NLog.Extensions.Hosting.Tests/ExtensionMethodTests.cs @@ -55,10 +55,12 @@ public void UseNLog_ShouldLogToNLog() [Fact] public void UseNLog_withConfiguration_WorksWithNLog() { - var memoryConfig = new Dictionary(); - memoryConfig["NLog:CaptureMessageProperties"] = "true"; - memoryConfig["NLog:CaptureMessageTemplates"] = "false"; - memoryConfig["NLog:IgnoreScopes"] = "false"; + var memoryConfig = new Dictionary + { + ["NLog:CaptureMessageProperties"] = "true", + ["NLog:CaptureMessageTemplates"] = "false", + ["NLog:IgnoreScopes"] = "false" + }; var someParam = new NLogProviderOptions { CaptureMessageProperties = false, CaptureMessageTemplates = false }; var actual = new HostBuilder().ConfigureHostConfiguration(config => config.AddInMemoryCollection(memoryConfig)).UseNLog(someParam).Build(); @@ -128,12 +130,14 @@ public void UseNLog_LoadConfigurationFromSection() { var host = new HostBuilder().ConfigureAppConfiguration((context, config) => { - var memoryConfig = new Dictionary(); - memoryConfig["NLog:Rules:0:logger"] = "*"; - memoryConfig["NLog:Rules:0:minLevel"] = "Trace"; - memoryConfig["NLog:Rules:0:writeTo"] = "inMemory"; - memoryConfig["NLog:Targets:inMemory:type"] = "Memory"; - memoryConfig["NLog:Targets:inMemory:layout"] = "${logger}|${message}|${configsetting:NLog.Targets.inMemory.type}"; + var memoryConfig = new Dictionary + { + ["NLog:Rules:0:logger"] = "*", + ["NLog:Rules:0:minLevel"] = "Trace", + ["NLog:Rules:0:writeTo"] = "inMemory", + ["NLog:Targets:inMemory:type"] = "Memory", + ["NLog:Targets:inMemory:layout"] = "${logger}|${message}|${configsetting:NLog.Targets.inMemory.type}" + }; config.AddInMemoryCollection(memoryConfig); }).UseNLog(new NLogProviderOptions() { LoggingConfigurationSectionName = "NLog", ReplaceLoggerFactory = true }).Build(); @@ -186,10 +190,12 @@ public void IHostApplicationBuilder_UseNLog_withOptionsParam_WorksWithNLog() [Fact] public void IHostApplicationBuilder_UseNLog_withConfiguration_WorksWithNLog() { - var memoryConfig = new Dictionary(); - memoryConfig["NLog:CaptureMessageProperties"] = "true"; - memoryConfig["NLog:CaptureMessageTemplates"] = "false"; - memoryConfig["NLog:IgnoreScopes"] = "false"; + var memoryConfig = new Dictionary + { + ["NLog:CaptureMessageProperties"] = "true", + ["NLog:CaptureMessageTemplates"] = "false", + ["NLog:IgnoreScopes"] = "false" + }; var someParam = new NLogProviderOptions { CaptureMessageProperties = false, CaptureMessageTemplates = false }; @@ -251,12 +257,14 @@ public void IHostApplicationBuilder_UseNLog_ReplaceLoggerFactory() [Fact] public void IHostApplicationBuilder_UseNLog_LoadConfigurationFromSection() { - var memoryConfig = new Dictionary(); - memoryConfig["NLog:Rules:0:logger"] = "*"; - memoryConfig["NLog:Rules:0:minLevel"] = "Trace"; - memoryConfig["NLog:Rules:0:writeTo"] = "inMemory"; - memoryConfig["NLog:Targets:inMemory:type"] = "Memory"; - memoryConfig["NLog:Targets:inMemory:layout"] = "${logger}|${message}|${configsetting:NLog.Targets.inMemory.type}"; + var memoryConfig = new Dictionary + { + ["NLog:Rules:0:logger"] = "*", + ["NLog:Rules:0:minLevel"] = "Trace", + ["NLog:Rules:0:writeTo"] = "inMemory", + ["NLog:Targets:inMemory:type"] = "Memory", + ["NLog:Targets:inMemory:layout"] = "${logger}|${message}|${configsetting:NLog.Targets.inMemory.type}" + }; var builder = new HostApplicationBuilder(); builder.Configuration.AddInMemoryCollection(memoryConfig); diff --git a/test/NLog.Extensions.Hosting.Tests/HostLayoutRendererTestHelper.cs b/test/NLog.Extensions.Hosting.Tests/HostLayoutRendererTestHelper.cs index b741dffe..727705b6 100644 --- a/test/NLog.Extensions.Hosting.Tests/HostLayoutRendererTestHelper.cs +++ b/test/NLog.Extensions.Hosting.Tests/HostLayoutRendererTestHelper.cs @@ -67,7 +67,7 @@ public string EnvironmentName internal sealed class EnvironmentVariableScope : IDisposable { - private readonly Dictionary _originalValues = new Dictionary(); + private readonly Dictionary _originalValues = []; public EnvironmentVariableScope(params string[] variableNames) { @@ -89,4 +89,4 @@ public void Dispose() Environment.SetEnvironmentVariable(variable.Key, variable.Value); } } -} \ No newline at end of file +} diff --git a/test/NLog.Extensions.Hosting.Tests/Properties/AssemblyInfo.cs b/test/NLog.Extensions.Hosting.Tests/Properties/AssemblyInfo.cs index d7f1e412..a8a87628 100644 --- a/test/NLog.Extensions.Hosting.Tests/Properties/AssemblyInfo.cs +++ b/test/NLog.Extensions.Hosting.Tests/Properties/AssemblyInfo.cs @@ -4,5 +4,3 @@ [assembly: Guid("a47d764d-c167-4bf2-bc60-d0d01eba9742")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1873:Avoid potentially expensive logging", Justification = "Unit Test has no performance concerns")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2253:Named placeholders should not be numeric values", Justification = "Unit Test has no performance concerns")] diff --git a/test/NLog.Extensions.Logging.Tests/ApiTests.cs b/test/NLog.Extensions.Logging.Tests/ApiTests.cs index 060c9567..50c53520 100644 --- a/test/NLog.Extensions.Logging.Tests/ApiTests.cs +++ b/test/NLog.Extensions.Logging.Tests/ApiTests.cs @@ -17,7 +17,7 @@ public class ApiTests { private readonly Type[] allTypes; private readonly Assembly nlogExtensionAssembly = typeof(NLogLoggerFactory).Assembly; - private readonly Dictionary typeUsageCount = new Dictionary(); + private readonly Dictionary typeUsageCount = []; public ApiTests() { @@ -149,7 +149,7 @@ public void AppDomainFixedOutput_Attribute_EnsureThreadAgnostic() if (appDomainFixedOutputAttribute != null) { var threadAgnosticAttribute = type.GetCustomAttribute(); - Assert.False(threadAgnosticAttribute is null, $"{type.ToString()} is missing [ThreadAgnostic] attribute"); + Assert.False(threadAgnosticAttribute is null, $"{type} is missing [ThreadAgnostic] attribute"); } } } @@ -164,7 +164,7 @@ public void WrapperLayoutRenderer_EnsureThreadAgnostic() if (type.IsAbstract || !type.IsPublic) continue; // skip non-concrete types, enumerations, and private nested types - Assert.True(type.IsDefined(typeof(ThreadAgnosticAttribute), true), $"{type.ToString()} is missing [ThreadAgnostic] attribute."); + Assert.True(type.IsDefined(typeof(ThreadAgnosticAttribute), true), $"{type} is missing [ThreadAgnostic] attribute."); } } } @@ -197,10 +197,10 @@ public void ValidateLayoutRendererTypeAlias() { // These class-names should be repaired with next major version bump // Do NOT add more incorrect class-names to this exlusion-list - HashSet oldFaultyClassNames = new HashSet() - { + HashSet oldFaultyClassNames = + [ "MicrosoftConsoleLayoutRenderer", - }; + ]; foreach (Type type in allTypes) { if (type.IsSubclassOf(typeof(LayoutRenderer))) diff --git a/test/NLog.Extensions.Logging.Tests/ConfigSettingLayoutRendererTests.cs b/test/NLog.Extensions.Logging.Tests/ConfigSettingLayoutRendererTests.cs index 25caccd1..212210ce 100644 --- a/test/NLog.Extensions.Logging.Tests/ConfigSettingLayoutRendererTests.cs +++ b/test/NLog.Extensions.Logging.Tests/ConfigSettingLayoutRendererTests.cs @@ -18,8 +18,10 @@ public void ConfigSettingFallbackDefaultLookup() [Fact] public void ConfigSettingSimpleLookup() { - var memoryConfig = new Dictionary(); - memoryConfig["Mode"] = "Test"; + var memoryConfig = new Dictionary + { + ["Mode"] = "Test" + }; ConfigSettingLayoutRenderer.DefaultConfiguration = new ConfigurationBuilder().AddInMemoryCollection(memoryConfig).Build(); var layoutRenderer = new ConfigSettingLayoutRenderer { Item = "Mode" }; var result = layoutRenderer.Render(LogEventInfo.CreateNullEvent()); @@ -29,8 +31,10 @@ public void ConfigSettingSimpleLookup() [Fact] public void ConfigSettingNestedLookup() { - var memoryConfig = new Dictionary(); - memoryConfig["Options:TableName"] = "Test"; + var memoryConfig = new Dictionary + { + ["Options:TableName"] = "Test" + }; ConfigSettingLayoutRenderer.DefaultConfiguration = new ConfigurationBuilder().AddInMemoryCollection(memoryConfig).Build(); var layoutRenderer = new ConfigSettingLayoutRenderer { Item = "Options.TableName" }; var result = layoutRenderer.Render(LogEventInfo.CreateNullEvent()); @@ -40,14 +44,16 @@ public void ConfigSettingNestedLookup() [Fact] public void ConfigSettingConfigEscapeLookup() { - var memoryConfig = new Dictionary(); - memoryConfig["Logging:Microsoft.Logging"] = "Test"; + var memoryConfig = new Dictionary + { + ["Logging:Microsoft.Logging"] = "Test" + }; ConfigSettingLayoutRenderer.DefaultConfiguration = new ConfigurationBuilder().AddInMemoryCollection(memoryConfig).Build(); var layoutRenderer = new ConfigSettingLayoutRenderer { Item = @"Logging.Microsoft\.Logging" }; var result = layoutRenderer.Render(LogEventInfo.CreateNullEvent()); Assert.Equal("Test", result); - var layoutRenderer2 = new ConfigSettingLayoutRenderer { Item = @"Logging.Microsoft..Logging" }; + var layoutRenderer2 = new ConfigSettingLayoutRenderer { Item = "Logging.Microsoft..Logging" }; var result2 = layoutRenderer2.Render(LogEventInfo.CreateNullEvent()); Assert.Equal("Test", result2); } diff --git a/test/NLog.Extensions.Logging.Tests/CustomBeginScopeTest.cs b/test/NLog.Extensions.Logging.Tests/CustomBeginScopeTest.cs index d568e06e..9e68c808 100644 --- a/test/NLog.Extensions.Logging.Tests/CustomBeginScopeTest.cs +++ b/test/NLog.Extensions.Logging.Tests/CustomBeginScopeTest.cs @@ -90,43 +90,35 @@ public async Task SayHello() public async Task SayHi() { - using (var scopeState = _logger.BeginScope("{World} People", "Earth")) - { - await Task.Yield(); - _logger.LogInformation("Hi"); - return scopeState.ToString(); - } + using var scopeState = _logger.BeginScope("{World} People", "Earth"); + await Task.Yield(); + _logger.LogInformation("Hi"); + return scopeState.ToString(); } public async Task SayHiToEarth() { - using (var scopeState = _logger.BeginScope("{Planet} in {Galaxy}", "Earth", "Milky Way")) - { - await Task.Yield(); - _logger.LogInformation("Hi"); - return scopeState.ToString(); - } + using var scopeState = _logger.BeginScope("{Planet} in {Galaxy}", "Earth", "Milky Way"); + await Task.Yield(); + _logger.LogInformation("Hi"); + return scopeState.ToString(); } public async Task SayNothing() { - using (var scopeState = _logger.BeginScope(new Dictionary())) - { - await Task.Yield(); - _logger.LogInformation("Nothing"); - } + using var scopeState = _logger.BeginScope(new Dictionary()); + await Task.Yield(); + _logger.LogInformation("Nothing"); } public async Task SaySomething() { - using (var scopeState = _logger.BeginScope(new Dictionary() + using var scopeState = _logger.BeginScope(new Dictionary() { { "Say", "Something" }, - })) - { - await Task.Yield(); - _logger.LogInformation("Say"); - } + }); + await Task.Yield(); + _logger.LogInformation("Say"); } } @@ -170,7 +162,7 @@ public override string ToString() { // We don't include the _action.Id here because it's just an opaque guid, and if // you have text logging, you can already use the requestId for correlation. - return string.Concat(_world, " People"); + return $"{_world} People"; } IEnumerator IEnumerable.GetEnumerator() diff --git a/test/NLog.Extensions.Logging.Tests/CustomLoggerPropertyTest.cs b/test/NLog.Extensions.Logging.Tests/CustomLoggerPropertyTest.cs index 82f88e47..499f561a 100644 --- a/test/NLog.Extensions.Logging.Tests/CustomLoggerPropertyTest.cs +++ b/test/NLog.Extensions.Logging.Tests/CustomLoggerPropertyTest.cs @@ -30,7 +30,7 @@ public void TestExtraMessageTemplatePropertySayHigh5() runner.SayHigh5(); Assert.Single(runner.GetTarget().Logs); - Assert.Equal(@"Hi 5|ActivityId=42", runner.GetTarget().Logs[0]); + Assert.Equal("Hi 5|ActivityId=42", runner.GetTarget().Logs[0]); } [Fact] @@ -42,7 +42,7 @@ public void TestExtraMessagePropertySayHi() runner.SayHigh5(); Assert.Single(runner.GetTarget().Logs); - Assert.Equal(@"Hi 5|ActivityId=42, 0=5", runner.GetTarget().Logs[0]); + Assert.Equal("Hi 5|ActivityId=42, 0=5", runner.GetTarget().Logs[0]); } private CustomLoggerPropertyTestRunner GetRunner(NLogProviderOptions options = null) @@ -105,7 +105,7 @@ public void SayHigh5() sealed class MyLogEvent : IReadOnlyList> { - private readonly List> _properties = new List>(); + private readonly List> _properties = []; private readonly Func _originalFormattter; private readonly TState _originalState; diff --git a/test/NLog.Extensions.Logging.Tests/Extensions/ConfigureExtensionsTests.cs b/test/NLog.Extensions.Logging.Tests/Extensions/ConfigureExtensionsTests.cs index f8037795..26959950 100644 --- a/test/NLog.Extensions.Logging.Tests/Extensions/ConfigureExtensionsTests.cs +++ b/test/NLog.Extensions.Logging.Tests/Extensions/ConfigureExtensionsTests.cs @@ -164,9 +164,11 @@ public void AddNLog_WithConfig_ReplaceLoggerFactory() { // Arrange ILoggingBuilder builder = new LoggingBuilderStub(); - var memoryConfig = new Dictionary(); - memoryConfig["Logging:NLog:ReplaceLoggerFactory"] = "True"; - memoryConfig["Logging:NLog:RemoveLoggerFactoryFilter"] = "True"; + var memoryConfig = new Dictionary + { + ["Logging:NLog:ReplaceLoggerFactory"] = "True", + ["Logging:NLog:RemoveLoggerFactoryFilter"] = "True" + }; var configuration = new ConfigurationBuilder().AddInMemoryCollection(memoryConfig).Build(); // Act diff --git a/test/NLog.Extensions.Logging.Tests/LoggerTests.cs b/test/NLog.Extensions.Logging.Tests/LoggerTests.cs index a6d0dadc..59a2fe9f 100644 --- a/test/NLog.Extensions.Logging.Tests/LoggerTests.cs +++ b/test/NLog.Extensions.Logging.Tests/LoggerTests.cs @@ -87,7 +87,7 @@ public void TestStructuredLoggingFormatter() public void TestSimulateStructuredLogging() { var runner = GetRunner(); - runner.Logger.Log(Microsoft.Extensions.Logging.LogLevel.Debug, default(EventId), new List>(new[] { new KeyValuePair("{OriginalFormat}", "message with id and {ParameterCount} property"), new KeyValuePair("ParameterCount", 1) }), null, (s, ex) => "message with id and 1 property"); + runner.Logger.Log(Microsoft.Extensions.Logging.LogLevel.Debug, default, new List>([new KeyValuePair("{OriginalFormat}", "message with id and {ParameterCount} property"), new KeyValuePair("ParameterCount", 1)]), null, (s, ex) => "message with id and 1 property"); Assert.Equal("NLog.Extensions.Logging.Tests.LoggerTests.Runner|DEBUG|message with id and 1 property|ParameterCount=1", runner.LastTargetMessage); } @@ -96,7 +96,7 @@ public void TestSimulateStructuredLogging() public void TestMessageProperties() { var runner = GetRunner(); - runner.Logger.Log(Microsoft.Extensions.Logging.LogLevel.Debug, default(EventId), new Dictionary { { "ParameterCount", "1" } }, null, (s, ex) => "message with id and 1 property"); + runner.Logger.Log(Microsoft.Extensions.Logging.LogLevel.Debug, default, new Dictionary { { "ParameterCount", "1" } }, null, (s, ex) => "message with id and 1 property"); Assert.Equal("NLog.Extensions.Logging.Tests.LoggerTests.Runner|DEBUG|message with id and 1 property|ParameterCount=1", runner.LastTargetMessage); } @@ -105,7 +105,7 @@ public void TestMessageProperties() public void TestMessagePropertiesList() { var runner = GetRunner(); - runner.Logger.Log(Microsoft.Extensions.Logging.LogLevel.Debug, default(EventId), new List>(new[] { new KeyValuePair("ParameterCount", "1") }), null, (s, ex) => "message with id and 1 property"); + runner.Logger.Log(Microsoft.Extensions.Logging.LogLevel.Debug, default, new List>([new KeyValuePair("ParameterCount", "1")]), null, (s, ex) => "message with id and 1 property"); Assert.Equal("NLog.Extensions.Logging.Tests.LoggerTests.Runner|DEBUG|message with id and 1 property|ParameterCount=1", runner.LastTargetMessage); } @@ -254,6 +254,7 @@ public void TestScopePropertyDictionary() Assert.Equal("NLog.Extensions.Logging.Tests.LoggerTests.Runner|DEBUG|message with id and 1 parameters|scope1=Hello", runner.LastTargetMessage); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2017", Justification = "Test intentionally verifies malformed format strings")] [Fact] public void TestInvalidFormatString() { @@ -262,6 +263,7 @@ public void TestInvalidFormatString() Assert.IsType(ex.InnerException); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2017", Justification = "Test intentionally verifies malformed format strings")] [Fact] public void TestInvalidFormatString2() { @@ -333,7 +335,7 @@ public void TestWithEmptyMessageAndNullException() var runner = GetRunner(); runner.Logger.LogDebug(20, (Exception)null, string.Empty); - var target = runner.GetTarget(); + var _ = runner.GetTarget(); Assert.Equal("NLog.Extensions.Logging.Tests.LoggerTests.Runner|DEBUG||EventId=20", runner.LastTargetMessage); } diff --git a/test/NLog.Extensions.Logging.Tests/Logging/NLogMessageParameterListTests.cs b/test/NLog.Extensions.Logging.Tests/Logging/NLogMessageParameterListTests.cs index 9894e662..a4a7cc47 100644 --- a/test/NLog.Extensions.Logging.Tests/Logging/NLogMessageParameterListTests.cs +++ b/test/NLog.Extensions.Logging.Tests/Logging/NLogMessageParameterListTests.cs @@ -47,16 +47,14 @@ public void GetEnumerator_StateUnderTest_ExpectedBehavior() // Arrange // Act - using (var enumerator = _messageParameterList.GetEnumerator()) - { - var list = new List(); - while (enumerator.MoveNext()) - list.Add(enumerator.Current); - var array = list.ToArray(); - - // Assert - AssertParameters(array); - } + using var enumerator = _messageParameterList.GetEnumerator(); + var list = new List(); + while (enumerator.MoveNext()) + list.Add(enumerator.Current); + var array = list.ToArray(); + + // Assert + AssertParameters(array); } [Fact] diff --git a/test/NLog.Extensions.Logging.Tests/MicrosoftConsoleJsonLayoutTests.cs b/test/NLog.Extensions.Logging.Tests/MicrosoftConsoleJsonLayoutTests.cs index ce85299c..4f2f80fe 100644 --- a/test/NLog.Extensions.Logging.Tests/MicrosoftConsoleJsonLayoutTests.cs +++ b/test/NLog.Extensions.Logging.Tests/MicrosoftConsoleJsonLayoutTests.cs @@ -21,7 +21,7 @@ public void MicrosoftConsoleJsonLayout_TimestampFormat() var layout = new MicrosoftConsoleJsonLayout() { TimestampFormat = "R" }; var logEvent = new LogEventInfo(LogLevel.Error, "MyLogger", "Hello World"); var result = layout.Render(logEvent); - Assert.Equal($"{{ \"Timestamp\": \"{logEvent.TimeStamp.ToUniversalTime().ToString("R")}\", \"EventId\": {0}, \"LogLevel\": \"Error\", \"Category\": \"MyLogger\", \"Message\": \"Hello World\", \"State\": {{ \"{{OriginalFormat}}\": \"Hello World\" }} }}", result); + Assert.Equal($"{{ \"Timestamp\": \"{logEvent.TimeStamp.ToUniversalTime():R}\", \"EventId\": {0}, \"LogLevel\": \"Error\", \"Category\": \"MyLogger\", \"Message\": \"Hello World\", \"State\": {{ \"{{OriginalFormat}}\": \"Hello World\" }} }}", result); } [Fact] @@ -40,14 +40,14 @@ public void MicrosoftConsoleJsonLayout_ExceptionEvent() var layout = new MicrosoftConsoleJsonLayout(); var exception = new ArgumentException("Test"); var eventId = 42; - var logEvent1 = new LogEventInfo(LogLevel.Error, "MyLogger", null, "Alert {EventId}", new object[] { eventId }, exception); + var logEvent1 = new LogEventInfo(LogLevel.Error, "MyLogger", null, "Alert {EventId}", [eventId], exception); var result1 = layout.Render(logEvent1); - Assert.Equal($"{{ \"Timestamp\": \"{logEvent1.TimeStamp.ToUniversalTime().ToString("O")}\", \"EventId\": {eventId}, \"LogLevel\": \"Error\", \"Category\": \"MyLogger\", \"Message\": \"Alert {eventId}\", \"Exception\": \"{exception.ToString()}\", \"State\": {{ \"{{OriginalFormat}}\": \"Alert {{EventId}}\" }} }}", result1); + Assert.Equal($"{{ \"Timestamp\": \"{logEvent1.TimeStamp.ToUniversalTime():O}\", \"EventId\": {eventId}, \"LogLevel\": \"Error\", \"Category\": \"MyLogger\", \"Message\": \"Alert {eventId}\", \"Exception\": \"{exception}\", \"State\": {{ \"{{OriginalFormat}}\": \"Alert {{EventId}}\" }} }}", result1); var eventId2 = 420; - var logEvent2 = new LogEventInfo(LogLevel.Error, "MyLogger", null, "Alert {EventId_Id}", new object[] { eventId2 }, exception); + var logEvent2 = new LogEventInfo(LogLevel.Error, "MyLogger", null, "Alert {EventId_Id}", [eventId2], exception); var result2 = layout.Render(logEvent2); - Assert.Equal($"{{ \"Timestamp\": \"{logEvent2.TimeStamp.ToUniversalTime().ToString("O")}\", \"EventId\": {eventId2}, \"LogLevel\": \"Error\", \"Category\": \"MyLogger\", \"Message\": \"Alert {eventId2}\", \"Exception\": \"{exception.ToString()}\", \"State\": {{ \"{{OriginalFormat}}\": \"Alert {{EventId_Id}}\" }} }}", result2); + Assert.Equal($"{{ \"Timestamp\": \"{logEvent2.TimeStamp.ToUniversalTime():O}\", \"EventId\": {eventId2}, \"LogLevel\": \"Error\", \"Category\": \"MyLogger\", \"Message\": \"Alert {eventId2}\", \"Exception\": \"{exception}\", \"State\": {{ \"{{OriginalFormat}}\": \"Alert {{EventId_Id}}\" }} }}", result2); } [Fact] @@ -64,10 +64,10 @@ public void MicrosoftConsoleJsonLayout_IncludeScopesEvent() var eventId = 42; using var requestScope = logger.PushScopeNested("Request Started"); using var activityScope = logger.PushScopeNested("Activity Started"); - var logEvent = new LogEventInfo(LogLevel.Error, null, null, "Alert {EventId}", new object[] { eventId }, exception); + var logEvent = new LogEventInfo(LogLevel.Error, null, null, "Alert {EventId}", [eventId], exception); logger.Log(logEvent); var result = logFactory.Configuration.FindTargetByName("test")?.Logs?.FirstOrDefault(); - Assert.Equal($"{{ \"Timestamp\": \"{logEvent.TimeStamp.ToUniversalTime().ToString("O")}\", \"EventId\": {eventId}, \"LogLevel\": \"Error\", \"Category\": \"{typeof(MicrosoftConsoleJsonLayoutTests).FullName}\", \"Message\": \"Alert {eventId}\", \"Exception\": \"{exception.ToString()}\", \"State\": {{ \"{{OriginalFormat}}\": \"Alert {{EventId}}\" }}, \"Scopes\": [ \"Request Started\", \"Activity Started\" ] }}", result); + Assert.Equal($"{{ \"Timestamp\": \"{logEvent.TimeStamp.ToUniversalTime():O}\", \"EventId\": {eventId}, \"LogLevel\": \"Error\", \"Category\": \"{typeof(MicrosoftConsoleJsonLayoutTests).FullName}\", \"Message\": \"Alert {eventId}\", \"Exception\": \"{exception}\", \"State\": {{ \"{{OriginalFormat}}\": \"Alert {{EventId}}\" }}, \"Scopes\": [ \"Request Started\", \"Activity Started\" ] }}", result); } [Fact] @@ -84,12 +84,12 @@ public void MicrosoftConsoleJsonLayout_IncludeActivityIds() // Act var _ = new System.Diagnostics.Activity("TestActivity").SetParentId("42").Start(); var eventId = 42; - var logEvent = new LogEventInfo(LogLevel.Info, "MyLogger", null, "Alert {EventId}", new object[] { eventId }); + var logEvent = new LogEventInfo(LogLevel.Info, "MyLogger", null, "Alert {EventId}", [eventId]); logger.Info(logEvent); // Assert var result = logFactory.Configuration.FindTargetByName("test")?.Logs?.FirstOrDefault(); - Assert.StartsWith($"{{ \"Timestamp\": \"{logEvent.TimeStamp.ToUniversalTime().ToString("O")}\", \"EventId\": {eventId}, \"LogLevel\": \"Information\", \"Category\": \"{typeof(MicrosoftConsoleJsonLayoutTests).FullName}\", \"Message\": \"Alert {eventId}\", \"State\": {{ \"{{OriginalFormat}}\": \"Alert {{EventId}}\" }}, \"TraceId\": \"42\", \"SpanId\": \"|42", result); + Assert.StartsWith($"{{ \"Timestamp\": \"{logEvent.TimeStamp.ToUniversalTime():O}\", \"EventId\": {eventId}, \"LogLevel\": \"Information\", \"Category\": \"{typeof(MicrosoftConsoleJsonLayoutTests).FullName}\", \"Message\": \"Alert {eventId}\", \"State\": {{ \"{{OriginalFormat}}\": \"Alert {{EventId}}\" }}, \"TraceId\": \"42\", \"SpanId\": \"|42", result); } } } diff --git a/test/NLog.Extensions.Logging.Tests/MicrosoftConsoleLayoutRendererTest.cs b/test/NLog.Extensions.Logging.Tests/MicrosoftConsoleLayoutRendererTest.cs index 0c65dbb3..1ddb8bf7 100644 --- a/test/NLog.Extensions.Logging.Tests/MicrosoftConsoleLayoutRendererTest.cs +++ b/test/NLog.Extensions.Logging.Tests/MicrosoftConsoleLayoutRendererTest.cs @@ -19,7 +19,7 @@ public void MicrosoftConsoleLayoutRenderer_ExceptionEvent() var layoutRenderer = new MicrosoftConsoleLayoutRenderer(); var exception = new ArgumentException("Test"); var eventId = 42; - var result = layoutRenderer.Render(new LogEventInfo(LogLevel.Error, "MyLogger", null, "Alert {EventId_Id}", new object[] { eventId }, exception)); + var result = layoutRenderer.Render(new LogEventInfo(LogLevel.Error, "MyLogger", null, "Alert {EventId_Id}", [eventId], exception)); Assert.Equal($"fail: MyLogger[{eventId}]{Environment.NewLine} Alert 42{Environment.NewLine}{exception}", result); } @@ -29,7 +29,7 @@ public void MicrosoftConsoleLayoutRenderer_OutOfMapperBoundsEventId() var layoutRenderer = new MicrosoftConsoleLayoutRenderer(); var exception = new ArgumentException("Test"); var eventId = 500; - var result = layoutRenderer.Render(new LogEventInfo(LogLevel.Error, "MyLogger", null, "Alert {EventId_Id}", new object[] { eventId }, exception)); + var result = layoutRenderer.Render(new LogEventInfo(LogLevel.Error, "MyLogger", null, "Alert {EventId_Id}", [eventId], exception)); Assert.Equal($"fail: MyLogger[{eventId}]{Environment.NewLine} Alert 500{Environment.NewLine}{exception}", result); } @@ -41,7 +41,7 @@ public void MicrosoftConsoleLayoutRenderer_TimestampFormat() var layoutRenderer = new MicrosoftConsoleLayoutRenderer() { TimestampFormat = timestampFormat }; var exception = new ArgumentException("Test"); var eventId = 42; - var logEvent = new LogEventInfo(LogLevel.Error, "MyLogger", null, "Alert {EventId}", new object[] { eventId }, exception); + var logEvent = new LogEventInfo(LogLevel.Error, "MyLogger", null, "Alert {EventId}", [eventId], exception); var result1 = layoutRenderer.Render(logEvent); Assert.Equal($"{logEvent.TimeStamp.ToString(timestampFormat)} fail: MyLogger[{eventId}]{Environment.NewLine} Alert 42{Environment.NewLine}{exception}", result1); } diff --git a/test/NLog.Extensions.Logging.Tests/MicrosoftILoggerTargetTests.cs b/test/NLog.Extensions.Logging.Tests/MicrosoftILoggerTargetTests.cs index 2a994bb6..0c71744b 100644 --- a/test/NLog.Extensions.Logging.Tests/MicrosoftILoggerTargetTests.cs +++ b/test/NLog.Extensions.Logging.Tests/MicrosoftILoggerTargetTests.cs @@ -251,7 +251,7 @@ private static (Logger, LoggerFactoryMock) CreateLoggerFactoryMock(out Microsoft sealed class LoggerFactoryMock : Microsoft.Extensions.Logging.ILoggerFactory { - public readonly Dictionary Loggers = new Dictionary(); + public readonly Dictionary Loggers = []; public void AddProvider(ILoggerProvider provider) { diff --git a/test/NLog.Extensions.Logging.Tests/NLogLoggingConfigurationTests.cs b/test/NLog.Extensions.Logging.Tests/NLogLoggingConfigurationTests.cs index dc274dc3..d0809cea 100644 --- a/test/NLog.Extensions.Logging.Tests/NLogLoggingConfigurationTests.cs +++ b/test/NLog.Extensions.Logging.Tests/NLogLoggingConfigurationTests.cs @@ -40,16 +40,17 @@ public void LoadSimpleConfig() [Fact] public void LoadConfigShouldIgnoreWellKnownEmptySections() { - var appSettings = @" -{ - ""NLog"": { - ""throwConfigExceptions"": true, - ""variables"": {}, - ""extensions"": [], - ""targets"": {}, - ""rules"": [] - } -}"; + var appSettings = """ + { + "NLog": { + "throwConfigExceptions": true, + "variables": {}, + "extensions": [], + "targets": {}, + "rules": [] + } + } + """; var logConfig = CreateNLogLoggingConfigurationWithNLogSection(appSettings); Assert.Empty(logConfig.LoggingRules); @@ -60,13 +61,14 @@ public void LoadConfigShouldIgnoreWellKnownEmptySections() [Fact] public void LoadConfigShouldThrowForUnrecognisedSections() { - var appSettings = @" -{ - ""NLog"": { - ""throwConfigExceptions"": true, - ""someRandomKey"": null - } -}"; + var appSettings = """ + { + "NLog": { + "throwConfigExceptions": true, + "someRandomKey": null + } + } + """; var ex = Assert.Throws(() => CreateNLogLoggingConfigurationWithNLogSection(appSettings)); Assert.Equal("Unrecognized value 'someRandomKey'='' for element 'NLog'", ex.Message); @@ -75,13 +77,14 @@ public void LoadConfigShouldThrowForUnrecognisedSections() [Fact] public void LoadConfigShouldThrowForUnrecognisedComplexSections() { - var appSettings = @" -{ - ""NLog"": { - ""throwConfigExceptions"": true, - ""someRandomKey"": {} - } -}"; + var appSettings = """ + { + "NLog": { + "throwConfigExceptions": true, + "someRandomKey": {} + } + } + """; var ex = Assert.Throws(() => CreateNLogLoggingConfigurationWithNLogSection(appSettings)); Assert.Equal("Unrecognized value 'someRandomKey'='' for element 'NLog'", ex.Message); @@ -460,12 +463,14 @@ private static NLogLoggingConfiguration CreateNLogLoggingConfigurationWithNLogSe private static Dictionary CreateMemoryConfigConsoleTargetAndRule(string sectionName = DefaultSectionName) { - var memoryConfig = new Dictionary(); - memoryConfig[$"{sectionName}:throwConfigExceptions"] = "true"; - memoryConfig[$"{sectionName}:Rules:0:logger"] = "*"; - memoryConfig[$"{sectionName}:Rules:0:minLevel"] = "Trace"; - memoryConfig[$"{sectionName}:Rules:0:writeTo"] = "File,Console"; - memoryConfig[$"{sectionName}:Targets:console:type"] = "Console"; + var memoryConfig = new Dictionary + { + [$"{sectionName}:throwConfigExceptions"] = "true", + [$"{sectionName}:Rules:0:logger"] = "*", + [$"{sectionName}:Rules:0:minLevel"] = "Trace", + [$"{sectionName}:Rules:0:writeTo"] = "File,Console", + [$"{sectionName}:Targets:console:type"] = "Console" + }; return memoryConfig; } diff --git a/test/NLog.Extensions.Logging.Tests/NLogMessageParameterListTests.cs b/test/NLog.Extensions.Logging.Tests/NLogMessageParameterListTests.cs index 3fbdbd10..aba633e9 100644 --- a/test/NLog.Extensions.Logging.Tests/NLogMessageParameterListTests.cs +++ b/test/NLog.Extensions.Logging.Tests/NLogMessageParameterListTests.cs @@ -95,7 +95,7 @@ public void CreateNLogMessageParameterMixedPositional() [Fact] public void TryParseShouldReturnEmptyListWhenInputIsEmpty() { - var items = new List> { }; + var items = new List>(); NLogMessageParameterList parsedList = NLogMessageParameterList.TryParse(items); var expectedCount = 0; diff --git a/test/NLog.Extensions.Logging.Tests/Properties/AssemblyInfo.cs b/test/NLog.Extensions.Logging.Tests/Properties/AssemblyInfo.cs index d58e4ad0..402b7ad2 100644 --- a/test/NLog.Extensions.Logging.Tests/Properties/AssemblyInfo.cs +++ b/test/NLog.Extensions.Logging.Tests/Properties/AssemblyInfo.cs @@ -11,5 +11,3 @@ [assembly: Xunit.CollectionBehavior(DisableTestParallelization = true)] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1873:Avoid potentially expensive logging", Justification = "Unit Test has no performance concerns")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2253:Named placeholders should not be numeric values", Justification = "Unit Test has no performance concerns")]