Bran
Bran

Reputation: 647

Removing Default Properties in Serilog Output

In the Serilog output in a file, I see that the default is

{
    "Timestamp": "2016-05-28T21:21:59.0932348+08:00",
    "Level": "Information",
    "MessageTemplate": "Processed {@Number} records in {@Time} ms",
    "Properties": {
        "Number": 500,
        "Time": 120
    }
}

Is there a way to remove the Timestamp, level, messagetemplate, and properties so that I"m left with this only

{
    "Number": 500,
    "Time": 120
}

The Log.Logger is assigned as such

Log.Logger = new LoggerConfiguration()
    .WriteTo.Sink(new FileSink(ConfigurationManager.AppSettings["serilogPath"], new JsonFormatter(), null))
    .CreateLogger();

Thanks

Upvotes: 11

Views: 6198

Answers (2)

Hakan Fıstık
Hakan Fıstık

Reputation: 19431

This question is old but now there is some easy solution for it, so I want to share them.

  1. Make sure you have this Serilog.Expressions Nuget Package (version 3.3 at least)

  2. You can now configure the ExpressionTemplate in code, here is an example:

    Log.Logger = new LoggerConfiguration()
        .WriteTo.Console(formatter: new ExpressionTemplate("{ {@t, @mt, @r, @l: if @l = 'Information' then undefined() else @l, @x, ..@p} }\n"))
        .CreateLogger();
    
  3. Or you can configure ExpressionTemplate in the appSettings.json, like this

    {
      "Name": "Console",
      "Args": {
        "formatter": {
          "type": "Serilog.Templates.ExpressionTemplate, Serilog.Expressions",
          "template": "[{@t:HH:mm:ss} {@l:u3} {Coalesce(SourceContext, '<none>')}] {@m}\n{@x}"
        }
      }
    }
    

Notes

  1. The formatter word in the appSettings is the name of an argument to a method, So it could be different depending on the sink you are using.
    For example, I used Mongodb Sink, so the name of the argument was mongoDBJsonFormatter for me

  2. I am not explaining the syntax of the ExpressionTemplate here, you can consult the following links for more info on that.

  3. here is a good article which explain this in more details

  4. here is Some documentation

Upvotes: 3

PatrickSteele
PatrickSteele

Reputation: 14677

From looking at the source code, it doesn't look like the JsonFormatter supports skipping those default properties. You could create your own ITextFormatter that does what you're looking for. Here's a quick example (that should not be used in production because it doesn't do any escaping -- it's just for demo purposes):

public class SOFormatter : ITextFormatter
{
    public void Format(LogEvent logEvent, TextWriter output)
    {
        output.Write("{");
        foreach (var p in logEvent.Properties)
        {
            output.Write("\"{0}\" : {1}, ", p.Key, p.Value);
        }
        output.Write("}");
    }
}

Upvotes: 6

Related Questions