Serilog:附加属性的使用

Serilog: Usage of additional properties

我正在尝试使用 {Properties}(不在消息模板中)将其他属性写入日志:

使用的 (FileSink) 模板:

"[{Level}] {Message}{NewLine}{Properties}{NewLine}{Exception}"

日志操作(简化,一般是对象数组由方法参数给定):

Log.Information("Start logging",
    new object[]{
        new { Version = "VersionString"},
        new { StartDate = DateTime.Now },
        new { Id = Guid.NewGuid() }
    });

我也累了:

Log.Information("Start logging",
    new object[]{
        "VersionString",
        DateTime.Now,
        Guid.NewGuid()
    });

我查看了 LogEventPropertyCapturingTests and this PR,但无法正常运行...


更新 我使用这样的包装函数:

public static void Information(string messageTemplate, object[] propertyValues, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumer = -1)
{
    using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumer }))
    {
        _MainLog.Information(messageTemplate, propertyValues);
    }

    if(show)
    {
        // Code to show a the event to the user
    }
}

Update2 找到了方法,但不是很好,因为模板-属性-匹配简陋

public static void Information(string messageTemplate, object[] propertyValues, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumer = -1)
{
    using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumer }))
    {
        Regex matchProperties = new Regex("{[^}]+}");

        int usedPropertiesCount = matchProperties.Matches(messageTemplate).Cast<Match>().Select(m => m.Value).Distinct().Count();

        if (propertyValues.Length > usedPropertiesCount)
        {
            using (LogContext.PushProperty("AdditionalData", propertyValues.Skip(usedPropertiesCount)))
            {
                _MainLog.Information(messageTemplate, propertyValues);
            }
        }
        else
        {
            _MainLog.Information(messageTemplate, propertyValues);
        }
    }

    if(show)
    {
        // Code to show a the event to the user
    }
}

ForContext() 方法将执行此操作:

Log.ForContext("Version", "VersionString")
    .ForContext("Id", Guid.NewGuid())
    .Information("Start logging");

(我省略了 StartDate,因为所有 Serilog 事件都已经加上了时间戳。)

This blog post series 包括一些关于消息模板的帖子以及涵盖此内容和其他替代方案的上下文和相关性。