如何在 .NET Core 3 Web 应用程序的代码中配置 NLog 以匹配 "Microsoft.*" 记录器名称但没有目标?
How do I configure NLog in code in a .NET Core 3 web app to match the "Microsoft.*" logger name and no target?
来自 Getting started with ASP.NET Core 3 的示例 nlog.config 有一个没有 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);
如何在代码中模拟此配置?
不幸的是,这在 API 中隐藏得更多。发送 null
作为目标将导致 ArgumentNullException
或 NullReferenceException
。所以那是行不通的。在这种情况下,您可以使用 NullTarget
(命名空间 NLog.Targets
)
您可以定义等效规则如下:
var blackhole = new NullTarget();
loggingConfiguration.AddRule(LogLevel.Trace, LogLevel.Info, blackhole, "Microsoft.*", true);
来自 Getting started with ASP.NET Core 3 的示例 nlog.config 有一个没有 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);
如何在代码中模拟此配置?
不幸的是,这在 API 中隐藏得更多。发送 null
作为目标将导致 ArgumentNullException
或 NullReferenceException
。所以那是行不通的。在这种情况下,您可以使用 NullTarget
(命名空间 NLog.Targets
)
您可以定义等效规则如下:
var blackhole = new NullTarget();
loggingConfiguration.AddRule(LogLevel.Trace, LogLevel.Info, blackhole, "Microsoft.*", true);