typestar

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

  1. Enrich.FromLogContext opts the pipeline into ambient properties.
  2. PushProperty scopes RequestId to the using block.
  3. The output template decides where pushed properties appear.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 2 in Logging with Serilog, step 7 of 16 in The open ecosystem.

← Previous Next →