【问题标题】:Serilog property enrichment but still required in call to actual write call?Serilog 属性丰富,但在调用实际写入调用时仍需要?
【发布时间】:2016-04-14 13:59:36
【问题描述】:

我正在将 Serilog 添加到我们的日志记录基础架构中,但对以下内容感到困惑:

public class OzCpWriteEntryExInput : OzCpAppServiceInputBase
{
    private readonly ILogger _Logger;

    /// <summary>
    ///     Class constructor
    /// </summary>
    public OzCpWriteEntryExInput(ILogger aLogger)
    {
        //Save params supplied
        _Logger = aLogger;

        //Create resources required
        Entry = new OzCpLogEntryContextInput();
    }

    public OzCpLogEntryContextInput Entry { get; set; }

    public ILogger Logger => _Logger;
}

public class OzCpLoggingService : OzCruisingPlatformAppServiceBase, IOzCpLoggingService
{
    private const string MESSAGE_TEMPLATE =
        "{LogVersion} {DateTimeUtc:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{LevelRange}] [{ApplicationHostName}] [{ApplicationName}] [{ApplicationVersion}] [{Location}] {Message}{NewLine}{Exception}{NewLine}{StackTrace}{NewLine}{UserDataKind}{@UserData}";

    public OzCpBuildLoggerOutput BuildLogger(OzCpBuildLoggerInput aParams)
    {
        OzCpBuildLoggerOutput result = new OzCpBuildLoggerOutput();
        //#TODO (DE) Convert logger hard coded values into settings
        bool logToUdp = true;

        //By default logging will include all events
        LoggerConfiguration loggerConfiguration = new LoggerConfiguration()
            .Enrich.WithProperty("LogVersion", "01.00")
            .MinimumLevel.Verbose();

        if (logToUdp)
        {
            loggerConfiguration.WriteTo.Udp(IPAddress.Loopback, 11000, 0, LogEventLevel.Verbose, MESSAGE_TEMPLATE);
        }

        //Finally we can build the logger
        result.Logger = loggerConfiguration.CreateLogger();

        return result;
    }

    /// <summary>
    ///     Writes an entry to the supplied logger and associated log sinks.
    /// </summary>
    /// <param name="aParams">Parameters defining the entry to be written.</param>
    /// <returns>Returns whether the entry was written to the logger.</returns>
    public OzCpWriteEntryExOutput WriteEntryEx(OzCpWriteEntryExInput aParams)
    {
        OzCpWriteEntryExOutput result = new OzCpWriteEntryExOutput();

        //These variable values are only the ones out of the entry as the logger "enriches" the other values based on
        //what has been passed in when it was configured
        object[] messageTemplateVariableValues =
        {
            "***",   //Log Version is actually an enriched property!!!!
            aParams.Entry.DateTimeUtc,
            aParams.Entry.LevelRange,
            aParams.Entry.Location,
            aParams.Entry.StackTrace,
            aParams.Entry.UserDataKind,
            aParams.Entry.UserData
        };

        switch (aParams.Entry.EntryKind)
        {
            case OzCpLoggingEntryKindEnum.Verbose:
                aParams.Logger.Verbose(aParams.Entry.Exception, MESSAGE_TEMPLATE, messageTemplateVariableValues);
                break;
        }

        return result;
    }
}

WriteLogEx() 的调用者最终可以提供自己的 Serilog.ILogger。我不会解释为什么会这样的原因,只是假设这是一个要求。

作为示例,我包括 BuildLogger(),它设置 ILogger 以使用自定义消息模板和一些通过丰富配置构建器的附加属性写入 UDP。

一切都非常简单。但是,现在当我使用 ILogger.Verbose() 写入 ILogger 时,我需要为消息模板中的令牌传递参数。

但这似乎是基于 ordinal 的,所以第一个进入 {LogVersion} 应该是通过扩充器完成的之前为记录器设置的配置。

如果我不使用 LogVersion,格式化的消息模板会减一,如果我包含它,那么我自然会得到:

*** 2016-04-14 14:53:57.677 +10:00 [信息]...

而不是我想要的是:

01.00 2016-04-14 14:53:57.677 +10:00 [信息]...

那么如何从 ILogger 中调用日志记录方法并通过名称而不是位置传递令牌值?

【问题讨论】:

    标签: c# .net serilog


    【解决方案1】:

    不要在.Verbose() 语句中传递这些,只需在其中传递特定于事件的数据。可以通过上下文化记录器来添加其他输出模板属性:

    var ctx = logger.ForContext("DateTimeUtc", aParams.Entry.DateTimeUtc)
                    .ForContext("LevelRange", aParams.Entry.LevelRange)
                    // and so-on.
    
    ctx.Verbose("Message here...");
    

    有一个ForContext() 重载接受PropertyEnrichers 的数组,我相信你可以用它来整理东西。

    【讨论】:

    • 这就是诀窍!然而让我感到困惑的是,当您执行 ctx.Verbose() 时,参数列表显示消息模板,我还注意到在处理异常时我会得到不同的行为。 1) .ForContext("Exception", aParams.Entry.Exception) 我没有得到异常标记的文本,但如果我使用 2) ctx.Verbose(aParams.Entry.Exception, aParams.Entry.Message);然后我得到了我所期望的 System.Exception: Dummy Exception。为什么 1) 会这样?
    • 想通了。做 1) 时需要将格式字符串更改为 @Exception 以便它序列化对象。都很好。
    • 只是手动构造一个LogEvent 并将其传递给记录器的Write() 方法,从长远来看可能不会那么混乱——绝对是一个值得探索的选择。祝你好运! :-)
    猜你喜欢
    • 2014-10-12
    • 1970-01-01
    • 1970-01-01
    • 2022-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-09
    • 2020-05-11
    相关资源
    最近更新 更多