Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 282
Menelaos Vergis Avatar asked Sep 04 '19 15:09

Menelaos Vergis


People also ask

Does Serilog support .NET core?

Serilog is a third-party, open-source library that integrates nicely with ASP.NET Core and allows developers to easily log-structured event data to the console, to files, and various kinds of log targets.

What is Serilog used for?

Introduction to Serilog Sinks Serilog Sinks are used to writing log events in various formats. Sinks are another name for data store using which we specify where we want to store log information for our application. The most common and popular sinks are consoles or files which are easy to configure.

What is LogContext Serilog?

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.

Is Serilog logger thread safe?

Yes, ILogger s in Serilog are always safe to use concurrently from multiple threads.


1 Answers

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.

like image 136
Nicholas Blumhardt Avatar answered Oct 04 '22 05:10

Nicholas Blumhardt