Search code examples
jsonasp.net-coreserilog

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?


Solution

  • I finally figured this out thanks to @Kraego. Here is how you can setup your logger using the Serilog.Expressions NuGet package:

    var logger = new LoggerConfiguration()
                .WriteTo.Console(
                    new ExpressionTemplate(
                        "{@t:yyyy-MM-dd HH:mm:ss.fff} [{@l}] {#if SourceContext is not null} ({SourceContext}){#end}\n{@m}{#if @x is not null}\n{@p}{#end}\n{@x}\n",
                        theme: TemplateTheme.Literate))
                .CreateLogger();
    

    In my case, I only wanted to print the properties (@p) in the case of an Exception, otherwise I just wanted the rendered message. Sample usage:

    logger.LogDebug("Sending {Count} records to Kafka broker for asset {AssetId}, session: {SessionId}", 1000, 1234, 5678);
    
    logger.LogWarning(exception, "An Exception was thrown during the processing of Data Source: {DataSource}. Retry attempt {Retry}/{MaxRetries}", "MyFileName.gz", 1, 3);
    

    and their corresponding output:

    2023-04-13 05:34:38.543 [Debug]  [MyNamespace.Pipeline.Kafka.KafkaMessagePublisher]
    Sending 1000 records to Kafka broker for asset 1234, session: 5678
    
    
    2023-04-13 05:34:39.666 [Warning]  [MyNamespace.Importer.Core.Processors.ProcessorPipeline]
    An Exception was thrown during the processing of Data Source: MyFileName.gz. Retry attempt 1/3
    <CUSTOM EXCEPTION PROPERTIES>
    <STACK TRACE>