Serilog 在输出中显示 属性 名称

Serilog show the property name in the output

如果我有这个:

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

我怎么输出这个:

this is a message with property_name = value

而不是:

this is a message with value

我认为你做不到。

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

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"
}

如果你想要 属性 的名字,我能想到的最快的方法是 CallerMemberName.

这是一个应用于函数调用的可选字符串参数的属性。它是在 .NET Framework 4.5 之后才添加的。而且我认为它与 INotify属性Changed:

一起为这种用途添加了很多
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")  
    {  
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }  

属性 名称字符串是 the Interface working 的基础。该界面几乎是 MVVM 的基础,因此与 WPF 和 UWP 紧密相关。 "Raise Event" 函数几十年来一直是标准函数 - 有时它们甚至只标记为受保护。

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

如果您的问题是关于 "how do I overwrite the concatenation rules for this logging System?":字符串连接。 String.Fomat() 或普通的旧 + 运算符。如果你给它完整的字符串来以你想要的精确格式登录,它什么也做不了,只能给你你想要的。

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

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

Formatting Output

Serilog provides several output formatting mechanisms.

  • Formatting plain text
  • Formatting JSON
  • Custom text formatters

使用 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)