【发布时间】:2023-01-13 04:37:51
【问题描述】:
我正在尝试根据全局设置的日志级别使用 NLog 记录到文件。我不确定这是否有可能从我能挖掘的一切中得到。
本质上,我想在我的appconfig.json 中有一个具有日志级别的全局设置。默认为Debug,但Trace 是另一个选项。如果我选择Debug,我想在名为log-debug.txt 的文件中记录从Debug 到Fatal 的所有内容。这似乎很合理;据我所知,这是基本教程案例,我已经完成了这项工作。
不过,这是另一件事:如果我将全局日志级别设置为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"
}
]
}
}
【问题讨论】: