问题
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 string
s 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