How to combine NLog Targets with Microsoft ILogger filters?

Viewed 531

We are using NLog in our .net 5.0 Web API and feel like log levels are set in multiple places. Is there a way we can configure nLog to use the app settings and ignore nLog.config log levels?

nlog.config:

<rules>
    <logger name="*" levels="Trace,Debug,Info,Warn,Error,Fatal" writeTo="NLogTarget"/>
</rules>

AppSettings.json:

"Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Debug"
    }
}

Thanks in advance.

1 Answers

If only using Microsoft ILogger then you can just use this in NLog (and rely on Microsoft LoggerFactory filtering from appsettings.json):

<rules>
    <logger name="*" writeTo="NLogTarget"/>
</rules>

Notice when upgrading to NLog 5.0, then remember to configure NLogProviderOptions.RemoveLoggerFactoryFilter = false on AddNLog or UseNLog (With latest NLog then the setting is already there, so you can set it upfront already now).

Most users gets confused by having 2 log-filtering systems, and expects when using NLog that it is NLog filters that applies. Therefore changed it to to ignore Microsoft LoggerFactory filters by default.

Notice you can also have the NLog config in appsettings.json. See also https://github.com/NLog/NLog.Extensions.Logging/wiki/NLog-configuration-with-appsettings.json

Related