【问题标题】:Add, enable and disable NLog loggers programmatically以编程方式添加、启用和禁用 NLog 记录器
【发布时间】:2026-01-31 06:55:01
【问题描述】:

如何在 NLog 的代码中添加、编辑、删除、启用和禁用记录器?

【问题讨论】:

    标签: c# nlog


    【解决方案1】:

    添加:

    var logTarget = new ...
    logTarget.Layout = "Your layout format here";
    // e.g. "${logger}: ${message} ${exception:format=tostring}";
    
    // specify what gets logged to the above target
    var loggingRule = new LoggingRule("*", LogLevel.Debug, logTarget);
    
    // add target and rule to configuration
    LogManager.Configuration.AddTarget("targetName", logTarget);
    LogManager.Configuration.LoggingRules.Add(loggingRule);
    LogManager.Configuration.Reload();
    

    删除完成

    LogManager.Configuration.LoggingRules.Remove(loggingRule);
    LogManager.Configuration.Reload();
    

    【讨论】:

    • @Stacker:这是一种非常迂回的做法。您已经拥有启用和禁用记录器的 API:添加或删除向它们提供日志事件的规则,如上所述。
    • 我喜欢你的方法,我知道如何重新加载配置,它通过添加以下内容:
    • @Stacker:很高兴听到你同时解决了它。干杯!
    • 我可以看到禁用或启用所有日志的最简单方法:LogManager.EnableLogging() 和 LogManager.DisableLogging()
    • @Stacker 根据文档 (nlog-project.org/documentation/v2.0.1/html/…) - Reload() 在配置更改时由 LogManager 调用,因此调用 LogManager.Configuration.Reload(); 不会重新加载配置。
    【解决方案2】:

    我知道这是一个旧答案,但我想为任何希望以编程方式修改其目标和日志记录规则的人提供反馈,因为 Configuration.Reload() 不起作用。

    要以编程方式更新现有目标,您需要使用 ReconfigExistingLoggers 方法:

    var target = (FileTarget)LogManager.Configuration.FindTargetByName("logfile");
    target.FileName = "${logDirectory}/file2.txt";
    LogManager.ReconfigExistingLoggers();
    

    动态添加和删除日志记录规则的示例:

    if (VerboseLogging && !LogManager.Configuration.LoggingRules.Contains(VerboseLoggingRule))
    {
        LogManager.Configuration.LoggingRules.Add(VerboseLoggingRule);
        LogManager.ReconfigExistingLoggers();
    }
    else if (!VerboseLogging && LogManager.Configuration.LoggingRules.Contains(VerboseLoggingRule))
    {
        LogManager.Configuration.LoggingRules.Remove(VerboseLoggingRule);
        LogManager.ReconfigExistingLoggers();
    }
    

    如文档中所写:

    循环遍历以前由 GetLogger 返回的所有记录器。和 重新计算他​​们的目标和过滤器列表。修改后有用 以编程方式配置以确保所有记录器都已 正确配置。

    此答案和示例来自 Tony 的答案:

    Update NLog target filename at runtime

    【讨论】:

    • 谢谢!我花了几个小时试图找出为什么我的配置更改没有传播到我的 Log 对象。 NLog 已经变得令人费解,恕我直言。
    【解决方案3】:

    NLog 4.6.7 可以将布局变量分配给 LoggingRule 级别,并在运行时更改这些布局变量。

    <nlog>
        <variable name="myLevel" value="Warn" />
        <rules>
          <logger minLevel="${var:myLevel}" />
        </rules>
    </nlog>
    

    然后你可以在代码中做到这一点:

    LogManager.Configuration.Variables["myLevel"] = "Debug";
    LogManager.ReconfigExistingLoggers();
    

    另请参阅:https://github.com/NLog/NLog/wiki/Filtering-log-messages#semi-dynamic-routing-rules

    【讨论】: