Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

.net

serilog

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.

like image 424
user1147862 Avatar asked Oct 30 '25 07:10

user1147862


1 Answers

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

like image 118
Nicholas Blumhardt Avatar answered Oct 31 '25 21:10

Nicholas Blumhardt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!