Skip to content
10 changes: 9 additions & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,12 @@ trim_trailing_whitespace = true

# .NET formatting rules
[*.{cs,vb}]
dotnet_sort_system_directives_first = true
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
48 changes: 28 additions & 20 deletions test/NLog.Extensions.Hosting.Tests/ExtensionMethodTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,12 @@ public void UseNLog_ShouldLogToNLog()
[Fact]
public void UseNLog_withConfiguration_WorksWithNLog()
{
var memoryConfig = new Dictionary<string, string>();
memoryConfig["NLog:CaptureMessageProperties"] = "true";
memoryConfig["NLog:CaptureMessageTemplates"] = "false";
memoryConfig["NLog:IgnoreScopes"] = "false";
var memoryConfig = new Dictionary<string, string>
{
["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();
Expand Down Expand Up @@ -128,12 +130,14 @@ public void UseNLog_LoadConfigurationFromSection()
{
var host = new HostBuilder().ConfigureAppConfiguration((context, config) =>
{
var memoryConfig = new Dictionary<string, string>();
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<string, string>
{
["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();

Expand Down Expand Up @@ -186,10 +190,12 @@ public void IHostApplicationBuilder_UseNLog_withOptionsParam_WorksWithNLog()
[Fact]
public void IHostApplicationBuilder_UseNLog_withConfiguration_WorksWithNLog()
{
var memoryConfig = new Dictionary<string, string>();
memoryConfig["NLog:CaptureMessageProperties"] = "true";
memoryConfig["NLog:CaptureMessageTemplates"] = "false";
memoryConfig["NLog:IgnoreScopes"] = "false";
var memoryConfig = new Dictionary<string, string>
{
["NLog:CaptureMessageProperties"] = "true",
["NLog:CaptureMessageTemplates"] = "false",
["NLog:IgnoreScopes"] = "false"
};

var someParam = new NLogProviderOptions { CaptureMessageProperties = false, CaptureMessageTemplates = false };

Expand Down Expand Up @@ -251,12 +257,14 @@ public void IHostApplicationBuilder_UseNLog_ReplaceLoggerFactory()
[Fact]
public void IHostApplicationBuilder_UseNLog_LoadConfigurationFromSection()
{
var memoryConfig = new Dictionary<string, string>();
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<string, string>
{
["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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public string EnvironmentName

internal sealed class EnvironmentVariableScope : IDisposable
{
private readonly Dictionary<string, string?> _originalValues = new Dictionary<string, string?>();
private readonly Dictionary<string, string?> _originalValues = [];

public EnvironmentVariableScope(params string[] variableNames)
{
Expand All @@ -89,4 +89,4 @@ public void Dispose()
Environment.SetEnvironmentVariable(variable.Key, variable.Value);
}
}
}
}
2 changes: 0 additions & 2 deletions test/NLog.Extensions.Hosting.Tests/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
12 changes: 6 additions & 6 deletions test/NLog.Extensions.Logging.Tests/ApiTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public class ApiTests
{
private readonly Type[] allTypes;
private readonly Assembly nlogExtensionAssembly = typeof(NLogLoggerFactory).Assembly;
private readonly Dictionary<Type, int> typeUsageCount = new Dictionary<Type, int>();
private readonly Dictionary<Type, int> typeUsageCount = [];

public ApiTests()
{
Expand Down Expand Up @@ -149,7 +149,7 @@ public void AppDomainFixedOutput_Attribute_EnsureThreadAgnostic()
if (appDomainFixedOutputAttribute != null)
{
var threadAgnosticAttribute = type.GetCustomAttribute<ThreadAgnosticAttribute>();
Assert.False(threadAgnosticAttribute is null, $"{type.ToString()} is missing [ThreadAgnostic] attribute");
Assert.False(threadAgnosticAttribute is null, $"{type} is missing [ThreadAgnostic] attribute");
}
}
}
Expand All @@ -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.");
}
}
}
Expand Down Expand Up @@ -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<string> oldFaultyClassNames = new HashSet<string>()
{
HashSet<string> oldFaultyClassNames =
[
"MicrosoftConsoleLayoutRenderer",
};
];
foreach (Type type in allTypes)
{
if (type.IsSubclassOf(typeof(LayoutRenderer)))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@ public void ConfigSettingFallbackDefaultLookup()
[Fact]
public void ConfigSettingSimpleLookup()
{
var memoryConfig = new Dictionary<string, string>();
memoryConfig["Mode"] = "Test";
var memoryConfig = new Dictionary<string, string>
{
["Mode"] = "Test"
};
ConfigSettingLayoutRenderer.DefaultConfiguration = new ConfigurationBuilder().AddInMemoryCollection(memoryConfig).Build();
var layoutRenderer = new ConfigSettingLayoutRenderer { Item = "Mode" };
var result = layoutRenderer.Render(LogEventInfo.CreateNullEvent());
Expand All @@ -29,8 +31,10 @@ public void ConfigSettingSimpleLookup()
[Fact]
public void ConfigSettingNestedLookup()
{
var memoryConfig = new Dictionary<string, string>();
memoryConfig["Options:TableName"] = "Test";
var memoryConfig = new Dictionary<string, string>
{
["Options:TableName"] = "Test"
};
ConfigSettingLayoutRenderer.DefaultConfiguration = new ConfigurationBuilder().AddInMemoryCollection(memoryConfig).Build();
var layoutRenderer = new ConfigSettingLayoutRenderer { Item = "Options.TableName" };
var result = layoutRenderer.Render(LogEventInfo.CreateNullEvent());
Expand All @@ -40,14 +44,16 @@ public void ConfigSettingNestedLookup()
[Fact]
public void ConfigSettingConfigEscapeLookup()
{
var memoryConfig = new Dictionary<string, string>();
memoryConfig["Logging:Microsoft.Logging"] = "Test";
var memoryConfig = new Dictionary<string, string>
{
["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);
}
Expand Down
40 changes: 16 additions & 24 deletions test/NLog.Extensions.Logging.Tests/CustomBeginScopeTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,43 +90,35 @@ public async Task SayHello()

public async Task<string> 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<string> 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<string, string>()))
{
await Task.Yield();
_logger.LogInformation("Nothing");
}
using var scopeState = _logger.BeginScope(new Dictionary<string, string>());
await Task.Yield();
_logger.LogInformation("Nothing");
}

public async Task SaySomething()
{
using (var scopeState = _logger.BeginScope(new Dictionary<string, object>()
using var scopeState = _logger.BeginScope(new Dictionary<string, object>()
{
{ "Say", "Something" },
}))
{
await Task.Yield();
_logger.LogInformation("Say");
}
});
await Task.Yield();
_logger.LogInformation("Say");
}
}

Expand Down Expand Up @@ -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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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)
Expand Down Expand Up @@ -105,7 +105,7 @@ public void SayHigh5()

sealed class MyLogEvent<TState> : IReadOnlyList<KeyValuePair<string, object>>
{
private readonly List<KeyValuePair<string, object>> _properties = new List<KeyValuePair<string, object>>();
private readonly List<KeyValuePair<string, object>> _properties = [];
private readonly Func<TState, Exception, string> _originalFormattter;
private readonly TState _originalState;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,9 +164,11 @@ public void AddNLog_WithConfig_ReplaceLoggerFactory()
{
// Arrange
ILoggingBuilder builder = new LoggingBuilderStub();
var memoryConfig = new Dictionary<string, string>();
memoryConfig["Logging:NLog:ReplaceLoggerFactory"] = "True";
memoryConfig["Logging:NLog:RemoveLoggerFactoryFilter"] = "True";
var memoryConfig = new Dictionary<string, string>
{
["Logging:NLog:ReplaceLoggerFactory"] = "True",
["Logging:NLog:RemoveLoggerFactoryFilter"] = "True"
};
var configuration = new ConfigurationBuilder().AddInMemoryCollection(memoryConfig).Build();

// Act
Expand Down
10 changes: 6 additions & 4 deletions test/NLog.Extensions.Logging.Tests/LoggerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<KeyValuePair<string, object>>(new[] { new KeyValuePair<string, object>("{OriginalFormat}", "message with id and {ParameterCount} property"), new KeyValuePair<string, object>("ParameterCount", 1) }), null, (s, ex) => "message with id and 1 property");
runner.Logger.Log(Microsoft.Extensions.Logging.LogLevel.Debug, default, new List<KeyValuePair<string, object>>([new KeyValuePair<string, object>("{OriginalFormat}", "message with id and {ParameterCount} property"), new KeyValuePair<string, object>("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);
}
Expand All @@ -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<string, object> { { "ParameterCount", "1" } }, null, (s, ex) => "message with id and 1 property");
runner.Logger.Log(Microsoft.Extensions.Logging.LogLevel.Debug, default, new Dictionary<string, object> { { "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);
}
Expand All @@ -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<KeyValuePair<string, object>>(new[] { new KeyValuePair<string, object>("ParameterCount", "1") }), null, (s, ex) => "message with id and 1 property");
runner.Logger.Log(Microsoft.Extensions.Logging.LogLevel.Debug, default, new List<KeyValuePair<string, object>>([new KeyValuePair<string, object>("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);
}
Expand Down Expand Up @@ -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()
{
Expand All @@ -262,6 +263,7 @@ public void TestInvalidFormatString()
Assert.IsType<FormatException>(ex.InnerException);
}

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2017", Justification = "Test intentionally verifies malformed format strings")]
[Fact]
public void TestInvalidFormatString2()
{
Expand Down Expand Up @@ -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);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,16 +47,14 @@ public void GetEnumerator_StateUnderTest_ExpectedBehavior()
// Arrange

// Act
using (var enumerator = _messageParameterList.GetEnumerator())
{
var list = new List<MessageTemplateParameter>();
while (enumerator.MoveNext())
list.Add(enumerator.Current);
var array = list.ToArray();

// Assert
AssertParameters(array);
}
using var enumerator = _messageParameterList.GetEnumerator();
var list = new List<MessageTemplateParameter>();
while (enumerator.MoveNext())
list.Add(enumerator.Current);
var array = list.ToArray();

// Assert
AssertParameters(array);
}

[Fact]
Expand Down
Loading
Loading