Search code examples
c#serilog

How to format Serilog JSON output in a very specific manner


I need to format the Serilog json output to file in a very specific format. I've messed with the outputtemplate but I must be missing something simple. An example of the output is:

{ 
    "event.action": "Save",
    "custom.vulnerability": "Save PII",
    "event.action":"Insert",
    "event.module":"Person",
    "message":"Inserted person object by Bob",
    "event.outcome":"Success",
    "host.ip":"192.168.0.0",
    etc...
}

Does anyone have any suggestions on how to achieve this format? I have enrichers to populate many of these properties but producing the desired output format is my issue. Thanks, Donta


Solution

  • In order to control the format of the JSON output you'll need to implement a custom ITextFormatter (where you decide how to format the JSON), and provide it to the sink(s) that are emitting the logs.

    Log.Logger = new LoggerConfiguration()
      .WriteTo.File(new YourCustomJsonFormatter(), "./logs/myapp.json")
      .CreateLogger();
    

    You can see an example implementation of a custom ITextFormatter in the source code of Serilog.Formatting.Compact.