更改代码 bedehing 中的 NLog 错误布局,而不是配置文件

Change the NLog error layout in code bedehing, not config file

我花了 2 个小时,但找不到解决方案:How to change the error layout for log.error(Exception, string) within the code (no config file)?

这只是一个随机配置,因为问题包含对输入或输出没有任何线索或要求(此外解决方案必须用代码实现)。这会将所有 Error-LogEvents 重定向到具有自己的自定义布局的单独文件。

var config = new NLog.Config.LoggingConfiguration();
    
// Targets where to log to: File and Console
var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "file.txt" };
var errorfile = new NLog.Targets.FileTarget("errorfile") { FileName = "error.txt" };
errorfile.Layout = "${longtime}|${level}|${message}|${exception}";
                
// Rules for mapping loggers to targets            
config.AddRule(LogLevel.Error, LogLevel.Fatal, errorfile, "*", true); // Final
config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile, "*");

// Apply config           
NLog.LogManager.Configuration = config;

您也可以让两个文件目标指向同一个文件,但这只有在使用 KeepFileOpen=false(默认)时才有可能。

或者,您可以使用 When-condition 来控制是否应包含其他输出。另见:https://github.com/NLog/NLog/wiki/When-Layout-Renderer