Search code examples
c#loggingserilog

BeginScope with Serilog


I want to use the feature the Microsoft.Logger has at Serilog directly, the BeginScope feature.

I know that I can use Microsoft ILogger and setup Serilog to be the underlying logger but it's too much trouble at this point of the app.

I want to know if there is a BeginScope equivalent in Serilog.

The information at the internet is not straight forward, there are mentions that Serilog support that but nowhere is mentioned if it's directly supported or by using the Microsoft classes.


Solution

  • Yes, Serilog has a native equivalent of this feature, called using LogContext.PushProperty().

    To enable this, you first must add Enrich.FromLogContext() to your Serilog LoggerConfiguration, for example:

    Log.Logger = new LoggerConfiguration()
        .Enrich.FromLogContext() // <- this line
        .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} " +
                                         "{Properties:j}{NewLine}{Exception}"))
        .CreateLogger();
    

    Then, to push properties onto the context (equivalent to ILogger.BeginScope()), use:

    using (LogContext.PushProperty("OrderId", 1234))
    {
        Log.Information("Processing a new order");
        // ...etc
    }
    

    The configuration above includes {Properties:j} to ensure all event properties, such as those from the log context, are included in the output. How you'll view the additional properties will depend upon which sink you're using.