15

What is the purpose of Serilog's @ syntax?

If I run the following:

var dummy = new { Foo = "Bar", Date = DateTime.Now };
Log.Information("Dummy object: {Dummy}", dummy);

Then I get an output to the console like so:

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

If I change the {Dummy} to {@Dummy} then I get the same output

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

So, what is the @ supposed to do?

BanksySan
  • 27,362
  • 33
  • 117
  • 216

1 Answers1

28

Look closely, and you'll see that it is not the same output.

The @ operator in front of Dummy tells Serilog to serialize the object passed in, rather than convert it using ToString(), which is what happens on your first example without using the @ operator.


Your log event in the first example will end up with a property like (here in JSON):

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

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

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

Comment from Nicholas Blumhardt (creator of 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!" :)

Community
  • 1
  • 1
C. Augusto Proiete
  • 24,684
  • 2
  • 63
  • 91
  • Yes! When you `ToString()` an anonymous type you get a serialized form. – BanksySan Jun 25 '16 at 16:21
  • 2
    @BanksySan Kind of... `ToString()` on an anonymous type still gives you a single string, it just looks nice. The `@` is much more than that as it provides the sink with the serialized object, and the sink can do whatever it wants with it, including storing the serialized data. Try using Serilog with Seq (https://getseq.net) to see how powerful the `@` operator can be. – C. Augusto Proiete Jun 26 '16 at 00:32
  • 1
    It only seems to serialize one level down, however. – John Feb 08 '23 at 17:45