7

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?

lonix
  • 14,255
  • 23
  • 85
  • 176
  • Hello @Ionix : I have almost the same problem and In can't find anywhere how to use a formatter and a custom template at the same time. Did you find a solution ? – kbaccouche Apr 01 '20 at 13:43
  • @kbaccouche Sorry my friend that was for an old project and I can't remember :-( I recall there was something relevant on the github repo... you might want to check there. Good luck! – lonix Apr 01 '20 at 14:24

1 Answers1

2

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.

lonix
  • 14,255
  • 23
  • 85
  • 176