【问题标题】:Custom ILogger Implementation and extra/custom fields?自定义 ILogger 实现和额外/自定义字段?
【发布时间】:2017-06-09 19:04:57
【问题描述】:

我已经从 .NET Core 中的 Microsoft.Extensions.Logging 包中编写了自己的 ILogger 实现,但是我不确定如何添加要记录的其他参数?

目前我的日志方法有以下签名:

    public void Log<TState>(
        LogLevel logLevel,
        EventId eventId,
        TState state,
        Exception exception,
        Func<TState, Exception, string> formatter)

如何扩展它以便可以传递额外的字段?它与 TState 参数有关吗?

我在这里here 找到了有关 LoggerMessage.Define 方法的一些附加信息,这听起来可能是我正在寻找的,但那里似乎没有太多信息。

【问题讨论】:

标签: c# .net .net-core


【解决方案1】:

如果你正在为接口编写实现,你应该只依赖接口(也许还有配置)。

要记录哪些“字段”将由格式化程序确定。您可以在您的实现中调用它并记录返回的字符串 - 如果提供的格式化程序为空,您可以在您的实现中提供您自己的基本格式化程序。

更简单的实现只需在状态上调用ToString() - 或进行某种序列化并记录结果。但这会剥夺调用者确定正在记录的内容的权力。

调试记录器可能如下所示:

    public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
    {
        formatter = formatter ?? ((o, ex) => string.Format("State: {0} - Exception: {1}", o, ex));
        Debug.WriteLine(this.Name + string.Format(" {0}: {1} - {2}", logLevel, eventId, formatter(state, exception)));
    }

【讨论】:

    猜你喜欢
    • 2019-04-28
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-13
    相关资源
    最近更新 更多