Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serilog with a custom template and JSON formatter

I'm using Serilog with ASP.NET Core 2.1, and configure it via the appsettings.json.

The default template doesn't include {SourceContext}, so I use my own template which includes it. But I also want structured logging with JSON.

I read somewhere in the Serilog wiki that I can't specify formatter (for JSON output) and outputTemplate at the same time.

So I can't do this for example:

"outputTemplate": "{Timestamp:yyyy-MM-dd} {Level:u3} {SourceContext} {Message:lj}{NewLine}{Exception}",
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact"

So how can I get JSON output, but also get the SourceContext data that I need?

like image 230
lonix Avatar asked Jul 06 '18 13:07

lonix


1 Answers

I'm unsure what's changed since the question was asked, but now I do get the SourceContext variable. I'm using Serilog.AspNetCore version 3.4.0, on ASP.NET Core 5.

This works:

{
  "Name": "File",
  "Args": {
    // ...
    //"outputTemplate": "",                          // DO NOT USE THIS
    "formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact"
  }
}

Just don't use outputTemplate and formatter at the same time.

This config gives me variables @t, @mt, @l, SourceContext.

Note @l is not included for Information level as that's considered the default.

like image 61
lonix Avatar answered Nov 10 '22 22:11

lonix