Log events can be enriched with properties in various ways. A number of pre-built enrichers are provided through NuGet:
Install-Package Serilog.Enrichers.Process
Install-Package Serilog.Enrichers.Environment
Install-Package Serilog.Enrichers.Thread
Configuration for enrichment is done via the Enrich
configuration object:
var log = new LoggerConfiguration() .Enrich.WithMachineName() .Enrich.WithThreadId() .Enrich.WithThreadName() .Enrich.WithProcessId() .Enrich.WithProcessName() .WriteTo.Console() .CreateLogger();
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"); }
References
https://github.com/serilog/serilog/wiki/Enrichment