Serilog: difference between {..} and {@..}

最后都变了- 提交于 2019-12-23 16:47:30

问题


Given this code:

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

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 { } ?

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


回答1:


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

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.

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



来源:https://stackoverflow.com/questions/24588571/serilog-difference-between-and

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!