Serilog:{..}和{@ ..}之间的区别

问题描述:

给出以下代码:

var d1 = new { x = 5, y = 88 };
Log.Logger.Information("{d1}", d1);
Log.Logger.Information("{@d1}", d1);

在d1中的对象如何在两行Log.Logger.Information(...)行中以不同的方式记录?换句话说,在{}之间添加@的作用是什么?

How will the object in d1 be logged differently in the two Log.Logger.Information(...) lines? In other words, what is the effect of adding the @ in between the { } ?

我阅读了 https://github.com/serilog/serilog/wiki/Structured-数据在保留对象结构"标题下,但这对我来说没有意义.

I read https://github.com/serilog/serilog/wiki/Structured-Data under the heading "Preserving Object Structure", but that didn't make sense to me.

{d1} 将无法识别的类型(如此处的匿名类型)转换为 string 进行记录,即使用 ToString().因此,在第一个示例中,您的日志事件将以一个类似(此处为JSON)的属性结尾:

{d1} converts unrecognized types like the anonymous one here into strings for logging, i.e. using ToString(). So your log event in the first example will end up with a property like (here in JSON):

{
  "d1": "{ x = 5, y = 88 }"
}

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

Using {@d1} will cause the parameter to be serialized as structured data:

{
  "d1":
  {
    "x": 5,
    "y": 88
  }
}

在适当的地方,第二个示例对于操作/分析更为有用.

Where appropriate, the second example is much more useful for manipulation/analysis.

之所以选择加入",是因为.NET程序中的大多数类型都可以很好地转换为字符串,但是没有可以完全/有意义地序列化.通过选择使用 @ 进行序列化,您的意思是:我知道我在做什么,序列化该对象!":)

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!" :)