代码之家  ›  专栏  ›  技术社区  ›  Luke

Serilog:附加属性的使用

  •  1
  • Luke  · 技术社区  · 7 年前

    我正在尝试使用{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 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
        }
    }
    

    更新2 找到了一种方法,但不是很好,因为模板属性匹配还很初级。

    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
        }
    }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Nicholas Blumhardt    7 年前

    这个 ForContext() 方法将执行以下操作:

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

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

    This blog post series 包括一些关于消息模板以及上下文和相关性的帖子,这些帖子涵盖了这一点以及其他备选方案。