【问题标题】:Change the NLog error layout in code bedehing, not config file更改代码隐藏中的 NLog 错误布局,而不是配置文件
【发布时间】:2021-04-19 14:57:39
【问题描述】:

我深了 2 小时但找不到解决方案:如何更改代码中 log.error(Exception, string) 的错误布局(无配置文件)?

【问题讨论】:

  • 您要写信给哪个目标?你写的是什么格式的纯文本、json、csv?你尝试了什么,什么失败了?
  • 目标是纯文本文件,我已经google了一个解决方案但找不到,所以我不知道如何找到。

标签: nlog


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    • 1970-01-01
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多