skip to content

In ASP.NET Core, how does ILogger.BeginScope tag each log line during one order's picking, and what makes that scope appear in console output?

level: middleimportance: should knowfreq 48%

answer

  1. using around the unit of work
  2. key/value pairs, not a plain string
  3. AsyncLocal, shared by every category
  4. IncludeScopes defaults to false
  5. framework scope: RequestId, RequestPath, TraceId

basics

~20 s

Wrap the work in using (logger.BeginScope(new Dictionary<string, object?> { ["OrderId"] = id })); every entry written inside it, by any logger and across awaits, carries OrderId. The console shows it only when IncludeScopes is true.

solid answer

~40 s

`BeginScope<TState>(TState state)` pushes a state object onto the logger factory's scope stack and returns an `IDisposable?` that pops it, so you put it in a `using` around the unit of work. Pass key/value pairs (a `Dictionary<string, object?>`, or a template such as `BeginScope("Order {OrderId}", orderId)`) so structured providers get an `OrderId` field rather than an opaque string. The stack lives in an `AsyncLocal`, so it flows across `await` and applies to **every** logger from the same factory, whatever its category: the `BinAllocator` you call inherits the order's scope. Providers decide whether to write scopes: the console formatters only do when `IncludeScopes` is `true` (default `false`), and the JSON formatter then adds a `Scopes` array. ASP.NET Core already opens scopes of its own: `SpanId`/`TraceId`/`ParentId`, `ConnectionId`, and `RequestId` with `RequestPath`.

code

csharp · 7 lines
csharp
builder.Logging.ClearProviders();
builder.Logging.AddJsonConsole(options =>
{
    options.IncludeScopes = true;                 // default is false
    options.TimestampFormat = "yyyy-MM-dd HH:mm:ss.fff";
    options.UseUtcTimestamp = true;
});

go deeper

for a junior

Recall that BeginScope goes in a using block and that its values appear on every line written inside it once the provider includes scopes.

for a middle

Explain the AsyncLocal stack shared across categories, why key/value state beats a string, the IncludeScopes default and the scopes ASP.NET Core opens for each request.

for a senior

Show where scopes stop flowing, such as channel consumers and background loops, and keep scope cost and nesting in check on high-volume paths.

for a principal

Decide which identifiers every service must put in scope so cross-service queries line up, and who owns that list as teams add fields.

## The problem a scope solves A picking service logs from several classes while it works through one order: the pick-list builder, the bin allocator, the label printer. Passing `orderId` into every log call of every class is noisy and easy to forget. A **log scope** attaches data to every entry written during a block of work instead. ```csharp public async Task PickAsync(Order order, CancellationToken ct) { using var scope = logger.BeginScope(new Dictionary<string, object?> { ["OrderId"] = order.Id, ["WaveId"] = order.WaveId }); logger.LogInformation("Picking {LineCount} lines", order.Lines.Count); await binAllocator.ReserveAsync(order, ct); // its own ILogger<BinAllocator> lines carry OrderId too } ``` ## How BeginScope works `ILogger.BeginScope<TState>(TState state) where TState : notnull` returns `IDisposable?`. The factory's `LoggerFactoryScopeProvider` keeps the current scope in an `AsyncLocal<Scope?>`, as a linked stack: - **Push and pop.** `BeginScope` pushes the state; disposing the returned object pops it. A `using` statement or `using var` guarantees the pop even when an exception escapes. `using` also copes with a `null` return, which loggers such as `NullLogger` give. - **Shared by every category.** The scope belongs to the logger factory, not to the logger that opened it, so a line written by `ILogger<BinAllocator>` inside the block carries the scope opened through `ILogger<PickListService>`. - **Flows with async code.** `AsyncLocal` travels with the execution context across `await` and into `Task.Run`. It does not travel to work that another long-running loop picks up later, such as a `BackgroundService` reading the order from a channel: that consumer's lines carry the consumer's own scopes. - **Nests.** An inner `BeginScope` adds to the outer ones; a provider that writes scopes walks the whole stack, outermost first. ## What to pass as the state | State passed | What a structured provider gets | |---|---| | `new Dictionary<string, object?> { ["OrderId"] = id }` | an `OrderId` key with the original value | | `BeginScope("Order {OrderId}", id)` | an `OrderId` key, plus the rendered text `Order 90211` | | `BeginScope($"Order {id}")` or a plain string | only a string; no field to filter on | The JSON console formatter checks whether the scope is an `IEnumerable<KeyValuePair<string, object?>>`. If it is, the scope becomes an object with a `Message` property (the state's `ToString()`) plus one property per pair; otherwise it becomes a plain string element of the `Scopes` array. ## Making scopes visible Scopes are captured by default (`LoggerFilterOptions.CaptureScopes` is `true`), but **each provider decides whether to write them**: 1. For the console, `ConsoleFormatterOptions.IncludeScopes` defaults to `false`. Turn it on with `AddJsonConsole(o => o.IncludeScopes = true)` or with `Logging:Console:FormatterOptions:IncludeScopes` set to `true` in configuration. 2. The simple console formatter then prints the scopes on an extra line joined with `=>`; the JSON formatter writes the `Scopes` array. 3. Providers that ignore scopes (the Debug provider, for example) never show them, whatever you configure. ## Scopes the framework opens for you With `IncludeScopes` on, a request's lines already carry several values before your code adds any: - `SpanId`, `TraceId` and `ParentId` from the current `Activity`, because the host sets `ActivityTrackingOptions` to those three flags; - `ConnectionId` from Kestrel's connection scope; - `RequestId` (the `HttpContext.TraceIdentifier`) and `RequestPath` from the hosting layer. Your order scope stacks on top of them, which is usually what makes the scope worth enabling: a single query on `OrderId` returns every line for that order, each still tied to its request and trace. ## Costs and mistakes - Forgetting to dispose a scope leaks it into every later line of the same async flow. - Opening a scope per loop iteration on a hot path allocates a state object each time; open it once per unit of work. - With `IncludeScopes` on, every written entry walks the scope stack, so deep nesting makes every line longer and slower to write.

  • Why does a dictionary scope serve a log store better than BeginScope($"Order {orderId}")?
    The JSON formatter writes a scope that is a sequence of key/value pairs as an object with one property per key, so `OrderId` becomes a field you can filter on. An interpolated string is just text: it lands in the `Scopes` array as a string element, and a query has to parse it. `BeginScope("Order {OrderId}", orderId)` also produces a pair.
  • An order is picked in a request, then handed to a BackgroundService through a channel for label printing. Do the printer's log lines carry the order's scope?
    No. The scope lives in an `AsyncLocal` on the request's execution context, and the background loop started long before the request with its own context. Open a new `BeginScope` with the `OrderId` inside the consumer when it dequeues the order.

A scope is a job ticket clipped to a picking cart: every item scanned while the ticket is clipped is recorded against that order, whichever picker scans it, and once the ticket is unclipped later scans carry nothing.

  • A scope only applies to lines from the logger that opened it.
  • BeginScope adds fields to the console as soon as it is called, with no configuration.
  • Scopes do not survive an await because the continuation may run on another thread.
  • A plain interpolated string scope gives the same queryable field as a dictionary.
  • There is no need to dispose a scope; it ends when the method returns.