I'm trying to configure NLog for a .NET 6 console app using the following appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning"
}
},
"NLog": {
"targets": {
"console": {
"type": "Console",
"layout": "${longdate} ${pad:padding=5:inner=${uppercase:${level}}} ${message}${onexception:inner=${newline}${exception:format=ToString}}"
}
},
"rules": [
{
"logger": "*",
"writeTo": "console",
"minLevel": "Trace"
}
]
}
}
Host.CreateDefaultBuilder(args)
.ConfigureLogging((context, logging) =>
{
var configuration = context.Configuration.GetSection("NLog");
if (!configuration.Exists())
return;
LogManager.Configuration = new NLogLoggingConfiguration(configuration);
logging.ClearProviders();
logging.AddNLog();
})
.ConfigureServices(services =>
{
services.AddHostedService<MyHostedService>();
})
.Build()
.Run();
The following code of the MyHostedService
works as expected with NLog.Extensions.Logging 1.7.5 - only messages at the Information
level and higher are displayed in the console.
private readonly ILogger<MyHostedService> _logger;
public MyHostedService(ILogger<MyHostedService> logger)
{
_logger = logger;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogTrace("Test");
_logger.LogDebug("Test");
_logger.LogInformation("Test");
_logger.LogWarning("Test");
_logger.LogError("Test");
_logger.LogCritical("Test");
return Task.CompletedTask;
}
But if 5.2.0 is installed then it outputs all messages. What am I doing wrong? Does NLog.Extensions.Logging 5.2.0 package require additional settings to consider Logging.LogLevel.Default
configuration option value?
CodePudding user response:
NLog v5 includes several breaking changes where one is NLog.Extensions.Logging without any filter
You can do this:
"NLog": {
"targets": {
"console": {
"type": "Console",
"layout": "${longdate} ${pad:padding=5:inner=${uppercase:${level}}} ${message}${onexception:inner=${newline}${exception:format=ToString}}"
}
},
"rules": [
{
"logger": "*",
"finalMinLevel": "Info"
},
{
"logger": "Microsoft*",
"finalMinLevel": "Warn"
},
{
"logger": "*",
"writeTo": "console",
"minLevel": "Trace"
}
]
}
Or you can do this:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning"
},
"NLog": {
"RemoveLoggerFactoryFilter": false
}
},
"NLog": {
"targets": {
"console": {
"type": "Console"
}
},
"rules": [
{
"logger": "*",
"writeTo": "console",
"minLevel": "Trace"
}
]
}
}
See also: https://github.com/NLog/NLog.Extensions.Logging/wiki/NLog-configuration-with-appsettings.json