Venkat
Venkat

Reputation: 855

How to combine NLog Targets with Microsoft ILogger filters?

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.

Upvotes: 5

Views: 2341

Answers (1)

Rolf Kristensen
Rolf Kristensen

Reputation: 19867

With NLog v5 then NLog.Extensions.Logging ignores the filters configured in Microsoft LoggerFactory from appsettings.json.

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

It is recommended to configure the filtering using the NLog-configuration, as it will give less surprises like this:

<rules>
    <logger name="System.*" finalMinLevel="Warn" />
    <logger name="Microsoft.*" finalMinLevel="Warn" />
    <logger name="Microsoft.Hosting.Lifetime*" finalMinLevel="Info" /> <!-- Overrides previous rule -->
    <logger name="*" minLevel="Debug" writeTo="NLogTarget" />
</rules>

You can also use ${configsetting} to resolve the default-loglevel from appsettings.json like this:

<rules>
    <logger name="System.*" finalMinLevel="Warn" />
    <logger name="Microsoft.*" finalMinLevel="Warn" />
    <logger name="Microsoft.Hosting.Lifetime*" finalMinLevel="Info" /> <!-- Overrides previous rule -->
    <logger name="*" minLevel="${configsetting:Logging.LogLevel.Default:whenEmpty=Debug}" writeTo="NLogTarget" />
</rules>

It is still possible to configure NLog to respect the filtering configured in Microsoft LoggerFactory (from appsettings.json), by configuring NLogProviderOptions.RemoveLoggerFactoryFilter = false when calling AddNLog or UseNLog. Then one can just do this:

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

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

Upvotes: 10

Related Questions