Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 456
Bran Avatar asked May 28 '16 14:05

Bran


2 Answers

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("}");
    }
}
like image 142
PatrickSteele Avatar answered Oct 18 '22 18:10

PatrickSteele


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

like image 24
Hakan Fıstık Avatar answered Oct 18 '22 20:10

Hakan Fıstık