【问题标题】:Choosing an NLog target based on global log level根据全局日志级别选择 NLog 目标
【发布时间】:2023-01-13 04:37:51
【问题描述】:

我正在尝试根据全局设置的日志级别使用 NLog 记录到文件。我不确定这是否有可能从我能挖掘的一切中得到。

本质上,我想在我的appconfig.json 中有一个具有日志级别的全局设置。默认为Debug,但Trace 是另一个选项。如果我选择Debug,我想在名为log-debug.txt 的文件中记录从DebugFatal 的所有内容。这似乎很合理;据我所知,这是基本教程案例,我已经完成了这项工作。

不过,这是另一件事:如果我将全局日志级别设置为Trace,我想要一切Trace 到登录log-trace.txt。我最初的想法是添加一个新的配置规则,所以我在 rules 集合中添加了第二个规则,但从我读过的所有内容来看,最终会在一个文件中包含调试消息,在另一个文件中包含跟踪消息。

这样做的目的是在极端情况下进行调试(即,用户不知道他们是如何进入该状态的,因此将设置从“调试”翻转为“跟踪”,再次使用它,当您遇到错误时将 log-trace.txt 发送给我),因此将调试和跟踪消息拆分到不同的文件中会达不到目的。

我该怎么做呢?

这是一个 WPF 应用程序,所以我在 app.xaml.cs 中使用它来设置全局级别:

serviceCollection.AddLogging(builder =>
{
    builder.ClearProviders();

    // Haven't written the code to pull it from the config file yet, but this is how
    // I would set it.
    builder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
    builder.AddNLog();
});

appconfig.json

{
  "settings": {
    "logLevel": "Debug"
  },
  "NLog": {
    "internalLogLevel": "Info",
    "autoReload": true,
    "targets": {
      "logfile-debug": {
        "type": "File",
        "fileName": "log-debug.txt",
        "layout": "${longdate}|${level}|${message}|${exception:format=tostring}"
      },
      "logfile-trace": {
        "type": "File",
        "fileName": "log-trace.txt",
        "layout": "${longdate}|${level}|${message}|${exception:format=tostring}",
      },
      "logconsole": {
        "type": "Debugger",
        "layout": "${longdate}|${level}|${message}|${exception:format=tostring}"
      }
    },
    "rules": [
      {
        "logger": "*",
        "minLevel": "Debug",
        "writeTo": "logfile-debug,logconsole"
      },
      {
        "logger": "*",
        "minLevel": "Trace",
        "writeTo": "logfile-trace,logconsole"
      }
    ]
  }
}

【问题讨论】:

    标签: c# wpf logging nlog


    【解决方案1】:

    你可以这样做:

    void EnableGlobalTrace(bool enable)
    {
       NLog.GlobalDiagnosticsContext.Set("GlobalTraceLevel", enable ? "Trace" : "Off");
       NLog.LogManager.ReconfigureExistingLoggers();
    }
    

    并有这样的规则:

        "rules": [
          {
            "logger": "*",
            "minLevel": "Debug",
            "writeTo": "logfile-debug,logconsole"
          },
          {
            "logger": "*",
            "minLevel": "${gdc:GlobalTraceLevel:whenEmpty=Off}",
            "writeTo": "logfile-trace"
          }
        ]
    

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

    另见:https://github.com/NLog/NLog/wiki/Environment-specific-NLog-Logging-Configuration

    【讨论】:

    • 这非常有效。唯一的缺点是调试文件是通过任何一种方式生成的,但我通过将您建议的跟踪规则应用于调试规则来解决了这个问题。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多