How to log complex object using Serilog in valid json format? How to log complex object using Serilog in valid json format? json json

How to log complex object using Serilog in valid json format?


Assuming you are using the file, rolling file or console sinks, you need to specify a JsonFormatter:

Log.Logger = new LoggerConfiguration()    .WriteTo.RollingFile(new JsonFormatter(), "myapp-{Date}.json")    .CreateLogger();

A few different JSON formats are supported by Serilog; see this post for discussion of some alternatives.


Make sure your Message template includes :lj format specifier at the end:

Log.Logger = new LoggerConfiguration()    .WriteTo.Console(outputTemplate:        "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")    .CreateLogger();

From documentation:

Message - The log event's message, rendered as plain text. The :l format specifier switches of quoting of strings, and :j uses JSON-style rendering for any embedded structured data.

On front docs page with JSON example there is no mention of it, took plenty of time for me to solve this problem too.