【问题标题】:Serilog show the property name in the outputSerilog 在输出中显示属性名称
【发布时间】:2019-12-03 01:18:35
【问题描述】:

如果我有这个:

logger.Information("this is a message with {property_name}", "value");

我怎么输出这个:

this is a message with property_name = value

代替:

this is a message with value

【问题讨论】:

    标签: c# serilog


    【解决方案1】:

    通过 Serilog 写入的日志消息的显示输出由您正在写入的 Sink 使用的 formatter 完成。每个接收器可以使用不同的格式化程序,并且可以以不同的方式表示输出。

    您所要求的不是默认格式化程序可以做到的,因此您必须编写自己的custom text formatter,然后告诉接收器使用您的格式化程序而不是默认格式化程序。

    Formatting Output

    Serilog 提供了多种输出格式化机制。

    • 格式化纯文本
    • 格式化 JSON
    • 自定义文本格式化程序

    【讨论】:

      【解决方案2】:

      使用structured logging,我们的想法是摆脱这种形式的公式化格式(这往往会被正则表达式解析),而是使用有意义的消息。

      如果您正在使用 Serilog 做类似这样的包或属性列表,一种技术是执行以下操作:

      Log.ForContext("property_name", propertyValue).Information("this is a message")
      

      然后确保在your outputTemplate 中使用Properties 令牌,例如

      var mt = "{LogLevel:u3} {SourceContext} {Message:l} {Properties}{NewLine}{Exception}"
      

      在配置 Sink 时使用它:

       .WriteTo.Console(outputTemplate: mt)
      

      【讨论】:

        【解决方案3】:

        如果您想要属性的名称,我能想到的最快方法是CallerMemberName

        这是您应用于函数调用的可选字符串参数的属性。它仅在 .NET Framework 4.5 之后添加。而且我认为它与 INotifyPropertyChanged 一起用于此用途:

            private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")  
            {  
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }  
        

        属性名称字符串是the Interface working 的基础。该接口几乎是 MVVM 的基础,因此与 WPF 和 UWP 紧密相关。 “引发事件”功能几十年来一直是标准的 - 有时它们甚至只标记为受保护。

        只要对 Logging 的调用具有围绕它的功能,您也可以轻松使用它。

        如果您的问题是关于“如何覆盖此日志记录系统的连接规则?”:字符串连接。 String.Fomat() 或普通的旧 + 运算符。如果你给它完整的字符串以你想要的精确格式登录,它除了给你想要的东西之外什么也做不了。

        【讨论】:

          【解决方案4】:

          我不认为你可以。

          你可以做你现在所做的,但使用明确定义的参数,然后得到你所要求的

          logger.Information("this is a message with property_name = {property_name}", "value");

          或者在哪里使用非渲染格式化程序

          logger.Information("this is a message with {property_name}", "value");

          将输出 JSON

          {
              "message": "this is a message with {property_name}"
              "property_name" : "value"
          }
          

          【讨论】:

            猜你喜欢
            • 2011-07-11
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-04-02
            • 1970-01-01
            相关资源
            最近更新 更多