如何使用文件记录器将 NLog 中的自定义静态字段记录到所有日志中?

时间:2021-05-31 15:35:26

标签: c# nlog

这个问题类似于 How do I log a custom field in NLog to database? ,但就我而言,我想在每个日志中记录相同的值。通常这将是一个硬编码的组件标识符,例如MAC 地址,我们在开始时读取一次并希望自动插入到所有日志中。

如果我遵循引用的答案,我可以执行以下操作: LogEventInfo theEvent = new LogEventInfo(logLevel, "", message); theEvent.Properties["ComponentID"] =MACADDRESS;`

log.Log(theEvent);

但我想避免必须为每个日志执行此操作。是否有某种方法可以通过使用 nlog 参数指定文件记录器的布局来自动获得此值:

<parameter name="@ComponentID" layout="${ComponentID}"/>

然后我会在代码中的某处设置值

2 个答案:

答案 0 :(得分:1)

您可以使用 NLog variable,但需要注意的是,如果更改 NLog 配置文件并启用自动重新加载功能,则该值将被重置:

LogManager.Configuration.Variables["ComponentID"] = "MACADDRESS";

文档提到它应该动态使用 (${var:ComponentID}) 而不是静态使用 (${ComponentID}),如果您要在运行时更改值。

实际上有一个名为 Global Diagnostic Context 的布局渲染器,其用途正是您所需要的。即使在上述情况下,该值也将保持不变。

GlobalDiagnosticsContext.Set("ComponentID","MACADDRESS");

像这样使用它:${gdc:item=ComponentID}

答案 1 :(得分:0)

您可以包装 NLog 类并将您的 MAC 地址添加到所有日志中。

public class MyLogger
{
    public static string MacAddress { get; set; }

    private NLog.Logger _logger;

    public MyLogger() : this(null) { }

    public MyLogger(string name)
    {
        _logger = NLog.LogManager.GetLogger(name ?? "");
    }

    public void Log(LogLevel level, string message, Exception exception = null)
    {
        if (level >= Manager.Instance.MinLevel)
        {
            var info = new NLog.LogEventInfo(level, _logger.Name, "<" + MacAddress + "> " + message);
            if (exception != null)
            {
                info.Exception = exception;
            }
            _logger.Log(typeof(NLogLogger), info);
        }
    }

    public void Trace(string message, Exception exception = null)
    {
        this.Log(LogLevel.Trace, message, exception);
    }

    public void Debug(string message, Exception exception = null)
    {
        this.Log(LogLevel.Debug, message, exception);
    }

    public void Info(string message, Exception exception = null)
    {
        this.Log(LogLevel.Info, message, exception);
    }

    public void Warn(string message, Exception exception = null)
    {
        this.Log(LogLevel.Warn, message, exception);
    }

    public void Error(string message, Exception exception = null)
    {
        this.Log(LogLevel.Error, message, exception);
    }

    public void Fatal(string message, Exception exception = null)
    {
        this.Log(LogLevel.Fatal, message, exception);
    }
}

然后你可以设置:

MyLogger.MacAddress = "XXX";