如何在.NET Core 3 Web应用程序中的代码中配置NLog,使其与 "Microsoft.*"记录器名称相匹配,且没有目标?

问题描述 投票:1回答:1

下面的例子是nlog.config 开始使用ASP.NET Core 3 的规则没有writeTo属性。

<!--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" />

唯一的重载 LoggingConfiguration.AddRule()LoggingConfiguration.AddRuleForAllLevels() 的最后一个参数需要一个非空的目标参数。

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

我如何在代码中模拟这种配置?

c# .net-core nlog
1个回答
1
投票

不幸的是,这在API中是比较隐蔽的。发送 null 作为目标,将导致 ArgumentNullExceptionNullReferenceException. 所以那是行不通的。在这种情况下,你可以使用 NullTarget (命名空间 NLog.Targets)

你可以将等价规则定义为:

var blackhole = new NullTarget();
loggingConfiguration.AddRule(LogLevel.Trace, LogLevel.Info, blackhole, "Microsoft.*", true); 
© www.soinside.com 2019 - 2024. All rights reserved.