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.
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.
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.
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.
Yes, ILogger s in Serilog are always safe to use concurrently from multiple threads.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With