Log context in C#
Push a property once; every event in the scope carries it.
using Serilog;
using Serilog.Context;
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Console(outputTemplate:
"[{Level:u3}] {RequestId} {Message:lj}{NewLine}")
.CreateLogger();
// everything logged inside the scope carries the pushed property
using (LogContext.PushProperty("RequestId", "req-7f3a"))
{
Log.Information("auth ok for {User}", "ada");
Log.Information("order saved");
}
Log.CloseAndFlush();
How it works
Enrich.FromLogContextopts the pipeline into ambient properties.PushPropertyscopesRequestIdto the using block.- The output template decides where pushed properties appear.
Keywords and builtins used here
newusing
The run, in numbers
- Lines
- 16
- Characters to type
- 429
- Tokens
- 70
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 49 seconds.
Step 2 of 2 in Logging with Serilog, step 7 of 16 in The open ecosystem.