Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Serilog, how can I remove empty brackets from JSON formatted log messages when using {Properties} format specifier?

I have the following outputTemplate string:

var formatString = "{NewLine}[{Timestamp:dd-MMM-yyyy HH:mm:ss}] {Level} {SourceContext}{NewLine}{Properties:j}{NewLine}{Message:lj}{NewLine}{Exception}";

I have several enrichers configured to add and remove properties. In the case when there are no properties to be logged I keep getting the empty JSON brackets on a line. For example when there are properties to log I get a log message like so:

[05-Jul-2019 07:13:57] Information Microsoft.AspNetCore.Mvc
{ "UserName": "SomeUser" }
This is some log message with a property that was not removed by any of the enrichers.

However, in the case when there are no properties I get this

[05-Jul-2019 07:13:57] Information Microsoft.AspNetCore.Mvc
{}
This is some log message that contains no properties

The empty JSON brackets {} are littered throughout my logs and just add noise. How can I extend or override Serilog to get rid of these brackets?

like image 859
Rob L Avatar asked Jul 05 '19 11:07

Rob L


1 Answers

You could use this serilog extension:

dotnet add package Serilog.Expressions

See github serilog-expressions: Conditional blocks: you can do something like ... {#if Property is not null} ({Property}){#end} ...

like image 152
kraego Avatar answered Oct 24 '22 06:10

kraego