Todd Heckel-MSFT
Todd Heckel-MSFT

Reputation: 83

How do I configure NLog in code in a .NET Core 3 web app to match the "Microsoft.*" logger name and no target?

The example nlog.config from Getting started with ASP.NET Core 3 has a rule with no writeTo property:

<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="allfile" />

<!--Skip non-critical Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" maxlevel="Info" final="true" /> <!-- BlackHole without writeTo -->
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />

The only overloads of LoggingConfiguration.AddRule() and LoggingConfiguration.AddRuleForAllLevels() with a final argument require a non-null target argument:

public void AddRule(LogLevel minLevel, LogLevel maxLevel, Target target, string loggerNamePattern, bool final);
public void AddRuleForAllLevels(Target target, string loggerNamePattern, bool final);

How do I emulate this configuration in code?

Upvotes: 1

Views: 660

Answers (1)

Julian
Julian

Reputation: 36800

Unfortunately this is a bit more hidden in the API. Sending null as target will result in a ArgumentNullException or NullReferenceException. So that won't work. In this case you could use the NullTarget (namespace NLog.Targets)

You could define the equivalent rule as follows:

var blackhole = new NullTarget();
loggingConfiguration.AddRule(LogLevel.Trace, LogLevel.Info, blackhole, "Microsoft.*", true); 

Upvotes: 2

Related Questions