Serilog property outside of message template

Viewed 831

I am currently using Serilog (Serilog.AspNetCore version 3.4.0) with a Loggly sink and I want to be able to write logs with a certain message template and properties that are not included in that template. I tried several variants but none seems to work:

_log.LogInformation("My message template", new {SeparateProperty = "Property value"});
_log.LogInformation(new {MyMessageTemplate = "My message template", SeparateProperty = "Property value"});

Where _log is an ILogger. How can I add properties to a log without having to include them in the message template?

2 Answers

You're looking for LogContext properties.


The LogContext

Serilog.Context.LogContext can be used to dynamically add and remove properties from the ambient "execution context"; for example, all messages written during a transaction might carry the id of that transaction, and so-on.

This feature must be added to the logger at configuration-time using .FromLogContext():

var log = new LoggerConfiguration()
    .Enrich.FromLogContext()

Then, properties can be added and removed from the context using LogContext.PushProperty():

log.Information("No contextual properties");

using (LogContext.PushProperty("A", 1))
{
    log.Information("Carries property A = 1");

    using (LogContext.PushProperty("A", 2))
    using (LogContext.PushProperty("B", 1))
    {
        log.Information("Carries A = 2 and B = 1");
    }

    log.Information("Carries property A = 1, again");
}

Pushing property onto the context will override any existing properties with the same name, until the object returned from PushProperty() is disposed, as the property A in the example demonstrates.

Important: properties must be popped from the context in the precise order in which they were added. Behavior otherwise is undefined.

ILogger<T>.BeginScope() can do this:

using (_log.BeginScope(new Dictionary<string, object>{
    ["SeparateProperty"] = "Property value"
}))
{
    _log.LogInformation("My message template");
}

See also this explanation.

Related