什么是 Serilog 解构?

What is Serilog destructuring?

Serilog @ 语法的目的是什么?

如果我运行以下内容:

var dummy = new { Foo = "Bar", Date = DateTime.Now };

Log.Information("Dummy object: {Dummy}", dummy);

然后我得到一个输出到控制台,像这样:

Time: 16:20 [Level: Information] (ManagedThreadID: 8) Message: Dummy object: "Foo = Bar, Date = 25/06/2016 16:20:30 }"

如果我将 {Dummy} 更改为 {@Dummy},那么我会得到相同的输出

Time: 16:22 [Level: Information] (ManagedThreadID: 8) Message: Dummy object:  Foo: "Bar", Date: 06/25/2016 16:22:28 }

那么,@ 应该做什么?

仔细看,你会发现这不是同一个输出。

Dummy 前面的 @ 运算符告诉 Serilog 序列化传入的对象,而不是使用 ToString() 转换它,这就是第一个示例中没有使用 [=12] 时发生的情况=]运算符。


您在第一个示例中的日志事件将以 属性 结尾(此处为 JSON):

{
  "Dummy": "{ Foo = Bar, Date = 25/06/2016 16:20:30 }"
}

使用{@Dummy}会导致参数被序列化为结构化数据:

{
  "Dummy":
  {
    "Foo": "Bar",
    "Date": "25/06/2016 16:20:30"
  }
}

Comment from Nicholas Blumhardt(Serilog 的创建者):

Where appropriate, using the @ operator is much more useful for manipulation/analysis.

The reason for this "opt-in" requirement is that most types in .NET programs convert nicely into strings, but aren't cleanly/meaningfully serializable. By opting in to serialization with @ you're saying: "I know what I'm doing, serialize this object!" :)