How can I create an optional property in a Serilog output template?

3.4k views Asked by At

I'm trying to create an global output template for serilog messages that follows the following format:

{Timestamp:yyyy-MM-dd HH:mm:ss,fff} [{ComponentName}, {ApplicationName}, {ThreadId}] {Level} ({ErrorId}): {Message} {Exception}

The trouble I'm running into is that, some messages will not contain error IDs, or exceptions, or ThreadIds. So, when this case occurs, I get a message that has a bunch of characters that add noise to the log message, e.g.,

2015-06-24 15:11:03,234 [Component, MyApp, ] Info (): This is a message that I'm writing

Is it possible to have Serilog support optional parameters in the message template?

2

There are 2 answers

0
C. Augusto Proiete On

You can use Serilog.Expressions to control the output using an ExpressionTemplate with conditional blocks so that only properties that are present are written to the output, including spaces and separators. e.g.

// using Serilog.Templates;

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console(new ExpressionTemplate(
        "[{@t:HH:mm:ss}{#if ErrorId is not null} ({ErrorId}){#end}"))
    .CreateLogger();
0
Mark West On

I am using Serilog in my application, and like you notice that "missing" fields will "disappear" as you observe, but the character formatting around these placeholders do not.

I recommend changing the format of the message template so that the fields that are optional either appear on subsequent lines (which can be ignored) or are formatted such that you don't notice their absence.

You could also write a wrapper around the Serilog logging methods (logger.Debug, logger.Warning, logger.Information, etc) that is called by your application, and which has logic (or overloaded methods) to know which values are present and which are absent. The wrapper code would provide an appropriate message template with the right combination to avoid extra characters in the message.