How can I include both "Message" and "MessageTemplate" in the Serilog JsonFormatter output?

Viewed 1293

I'm using Serlog 2.10, Writing to Console (as human-readable text), and to RollingFile - with JsonFormatter.

I want in the output JSON to have both: "Message" and "MessageTemplate" nodes,

However I'm getting only either "Message" or "MessageTemplate", but not both.

Here's how it's being configured:

Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Information()
                .WriteTo.Console()
                .WriteTo.RollingFile(new JsonFormatter(), "logs/log-{Date}.log")
                .CreateLogger();

I followed the instructions on this page: https://github.com/serilog/serilog-formatting-compact

I've tried all 3 Json Formatters:

  • "RenderedCompactJsonFormatter" - puts "@m" (Message) in the output
  • "CompactJsonFormatter" - puts "@mt" (MessageTemlate) in the output
  • "JsonFormatter" - puts "MessageTemplate" in the output

How can I include both of them in the output?

Any assistance would be appreciated

2 Answers

One way is to write your own formatter. Start from e.g. the JsonFormatter and only use those parts that are valid for your requirements.

Serilog.Expressions can do this:

  .WriteTo.RollingFile(
    new ExpressionTemplate(
      "{ {Timestamp: @t, Level: @l, MessageTemplate: @mt, Message: @m, Exception: @x, " +
      "Properties: if IsDefined(@p[?]) then @p else undefined()} }" + Environment.NewLine,
      "logs/log-{Date}.log")
Related