【问题标题】:NLog filter by LogLevel as MappedDiagnosticsContextNLog 按 LogLevel 过滤为 MappedDiagnosticsContext
【发布时间】:2014-04-11 21:36:29
【问题描述】:

根据这里的答案:How Thread-Safe is NLog? 我创建了一个 Logger 并向 NLog 添加了两个 MappedDiagnosticsContext:

NLog.MappedDiagnosticsContext.Set("Module", string.Format("{0}.{1}", module.ComputerName, module.ModuleType));
NLog.MappedDiagnosticsContext.Set("ModuleCoreLogLevel", string.Format("LogLevel.{0}", module.CoreLogLevel));

我可以成功地使用 NLog 配置中的“模块”上下文(以编程方式)生成记录器应该记录到的文件名:

${{when:when=length('${{mdc:Module}}') == 0:inner=UNSPECIFIED}}${{when:when=length('${{mdc:Module}}') > 0:inner=${{mdc:Module}}}}.txt

这会记录例如所有带有“测试”的“模块”上下文的消息到一个名为 Module.txt

的文件名

我现在希望能够使用这种方式为不同的模块设置 LogLevel,并且只记录与此 LogLevel(或更高)对应的消息

我正在尝试通过过滤器来做到这一点,这意味着,在 LoggingRule 上我正在尝试添加一个过滤器:

rule92.Filters.Add(new ConditionBasedFilter { Condition = "(level < '${mdc:ModuleCoreLogLevel}')", Action = FilterResult.IgnoreFinal });

然而,这似乎并没有过滤消息。 例如,如果我有一条使用 Logger.Trace() 发出的消息,并且“ModuleCoreLogLevel”上的 LogLevel 设置为 LogLevel.Debug,我仍然可以在生成的 LogFile 中显示消息。

【问题讨论】:

  • 我想我通过为每个级别执行此操作解决了这个问题:rule92.Filters.Add(new ConditionBasedFilter { Condition = "(equals('${mdc:ModuleCoreLogLevel}', 'LogLevel.Trace') and level &lt; LogLevel.Trace)", Action = FilterResult.IgnoreFinal }); 任何更好/更快的想法? :)

标签: c# nlog


【解决方案1】:

我通过对每个级别都这样做来解决这个问题:

rule92.Filters.Add(new ConditionBasedFilter { Condition = "(equals('${mdc:ModuleCoreLogLevel}', 'LogLevel.Trace') and level < LogLevel.Trace)", Action = FilterResult.IgnoreFinal });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多