skip to content

In Serilog, how do Enrich.WithProperty, ForContext and LogContext.PushProperty attach a property such as a shipment id, and why does PushProperty need Enrich.FromLogContext()?

level: middleimportance: should knowfreq 50%

answer

  1. WithProperty: every event, whole logger
  2. ForContext returns a new ILogger
  3. PushProperty returns IDisposable
  4. AsyncLocal stack, innermost wins
  5. template property beats context

basics

~20 s

Enrich.WithProperty adds a fixed property to every event, ForContext returns a logger whose events carry it, and LogContext.PushProperty adds it to all events in an async scope until disposed. PushProperty only reaches events if Enrich.FromLogContext() is configured.

solid answer

~40 s

Serilog has three ways to add a property that is not in the template. `Enrich.WithProperty("Service", "courier-api")` is set at configuration time and stamps **every** event. `logger.ForContext("TrackingNumber", number)` returns a **new `ILogger`** whose events carry the property; `ForContext<T>()` does the same for `SourceContext`. `LogContext.PushProperty("TrackingNumber", number)` pushes onto an **ambient**, `AsyncLocal`-based stack that flows across `await`, and returns an `IDisposable` that pops it - so wrap it in `using`. The ambient stack is only read by the `LogContextEnricher`, which `Enrich.FromLogContext()` installs; without that call, pushes are silently ignored. All three use add-if-absent: a property already on the event, such as a template hole with the same name, wins, and for duplicate pushes the innermost wins.

go deeper

for a junior

Know the pattern: Enrich.FromLogContext() in configuration, then using (LogContext.PushProperty(...)) around the work.

for a middle

Compare WithProperty, ForContext and PushProperty by scope and lifetime, explain the AsyncLocal stack and the add-if-absent precedence.

for a senior

Diagnose missing context: absent FromLogContext, disposal order, work handed to another flow, and use LogContext.Clone to carry it across a queue.

for a principal

Define the small set of context properties every service must carry and where they are pushed, so cross-service queries work.

## Why enrich at all A message template captures what one call site knows. Other context - which shipment is being processed, which service is running, which component is logging - is the same for many events. **Enrichment** adds such properties without repeating them in every template, so a query for one tracking number returns every event about it. ## The three tools | Tool | Set where | Applies to | Lifetime | |---|---|---|---| | `Enrich.WithProperty(name, value)` | `LoggerConfiguration` | every event of the logger | the logger's life | | `logger.ForContext(name, value)` | at a call site | events written through the returned logger | as long as you keep that logger | | `LogContext.PushProperty(name, value)` | at a call site | every event in the current async flow, through any logger with `Enrich.FromLogContext()` | until the returned `IDisposable` is disposed | All three take an optional `destructureObjects` flag, which captures the value as if with `@`. ## ForContext `ForContext` never changes the logger you call it on; it returns a new `ILogger` with a fixed property: ```csharp var log = Log.ForContext<ShipmentProcessor>() .ForContext("TrackingNumber", shipment.TrackingNumber); log.Information("Label printed"); log.Information("Handed to courier {CourierId}", courierId); ``` Both events carry `TrackingNumber`, plus `SourceContext` set to the full name of `ShipmentProcessor`, which is also what minimum-level overrides match. The property only travels as far as that logger object is passed. ## LogContext `LogContext` is ambient: code deep in the call chain does not need the logger that the outer code enriched. ```csharp using (LogContext.PushProperty("TrackingNumber", shipment.TrackingNumber)) { await _labels.PrintAsync(shipment); // its logs carry TrackingNumber await _dispatch.AssignAsync(shipment); // so do these } ``` How it works, from the source: 1. The context is an immutable stack held in an `AsyncLocal`, so it follows the logical flow across `await` and into tasks started from it. 2. `PushProperty` pushes a property enricher and returns a bookmark; disposing it restores the stack as it was, popping anything pushed on top as well. Dispose in reverse order - a `using` does that for you. 3. Nothing reads the stack unless the logger was configured with `Enrich.FromLogContext()`. Forgetting it is the classic reason pushed properties never appear, and nothing warns you. 4. When the same name is pushed twice, the innermost push wins, because the stack is applied from the top with add-if-absent. `LogContext` also offers `Push(ILogEventEnricher)` for arbitrary enrichers, `Clone()` to capture the current context as an enricher that can be re-applied elsewhere (for example on a queued work item), and `Suspend()` and `Reset()` to hide or clear it. ## Precedence Enrichers add a property **only if it is absent**. So: - a template hole `{TrackingNumber}` on the event beats a pushed or `ForContext` property of the same name; - among pushed properties, the innermost wins. This is predictable but can surprise: a pushed `Status` silently loses to a template that also says `{Status}`. ## Conditional enrichment `Enrich.When(predicate, configure)` and `Enrich.AtLevel(level, configure)` apply an enricher only to some events - for instance adding a costly property only to warnings and above. ## Common failure modes - **No `Enrich.FromLogContext()`** - every push is silently ignored. - **Push without `using`** - the property leaks into later, unrelated events on the same flow. - **Work handed to another flow** - a queue consumer or a timer callback does not see the producer's context; carry it with `LogContext.Clone()`. - **Name collisions** - a template hole or an outer push with the same name wins or loses by the add-if-absent rule, not by recency of the code you are reading. - **Large objects with `destructureObjects: true`** - the same destructuring costs apply as with `@`, now on every event in scope. ## Choosing - Process-wide constants (service name, version): `Enrich.WithProperty`. - Component identity and values tied to one object you pass around: `ForContext`. - Values that must reach code you do not control, across an async call chain: `LogContext.PushProperty` with `Enrich.FromLogContext()`.

  • A background consumer reads shipments from a queue and its logs lack the TrackingNumber pushed by the producer. Why, and what fixes it?
    The `LogContext` flows with the async call chain that pushed it, and the consumer runs on a different flow. Capture it at enqueue time with `LogContext.Clone()`, store the returned enricher with the work item, and re-apply it in the consumer with `using (LogContext.Push(enricher))` or `log.ForContext(enricher)`. Or simply push the id again in the consumer.
  • Why does a pushed Status property not show up on an event whose template contains {Status}?
    Enrichers use add-if-absent semantics. The template already created a `Status` property from the argument, so the context enricher leaves it alone. The template value wins; rename one of them if both are needed.
  • What happens if the IDisposable from PushProperty is never disposed?
    The property stays on the context for the rest of that async flow, so unrelated later events carry a stale value. Disposing an outer bookmark also pops anything pushed above it, so out-of-order disposal can remove properties early. Always pair the push with `using`.

  • LogContext.PushProperty works without any enricher configuration
  • ForContext adds the property to the static Log.Logger for everyone
  • A pushed property overrides a template property with the same name
  • LogContext is per thread, so it is lost after every await
  • The outermost PushProperty wins when the same name is pushed twice