Log scopes and correlation in ASP.NET Core: ILogger.BeginScope and scope providers, the hosting scope (RequestId, RequestPath), ActivityTrackingOptions adding TraceId and SpanId, System.Diagnostics.Activity and AsyncLocal flow, W3C Trace Context (traceparent, tracestate, baggage), automatic propagation through HttpClient, propagating through Azure Service Bus messages, and when a business correlation ID is still useful.
Two mechanisms work together.
using (logger.BeginScope(new Dictionary<string, object> { ["OrderId"] = id })) adds properties to every log inside the block, flowing across await via AsyncLocal. ASP.NET Core already opens a scope per request with RequestId and RequestPath.Activity whose trace id comes from the incoming W3C traceparent header or is created new. With ActivityTrackingOptions (on by default in the Generic Host) every log carries TraceId and SpanId. HttpClient propagates traceparent automatically; message queues need it copied into message properties (the Azure Service Bus SDK does this).So the trace id is your correlation id; add business ids as properties. The trade-off: custom correlation headers are easy but don't interoperate with tracing tools.
"For one service, the tool is the log scope.
logger.BeginScope(...)pushes a set of properties onto an async-local stack, and every log written inside thatusingblock, in any class, gets those properties if the provider supports scopes. ASP.NET Core already opens one per request withRequestId,RequestPathand the connection id. I add my own for business context, likeOrderIdin a message handler, so I don't have to repeat it in every template.Across services, the standard is W3C Trace Context. Every incoming request gets an
Activity, and if the caller sent atraceparentheader, the activity continues that trace, same trace id, new span id. The Generic Host setsActivityTrackingOptionsto includeTraceId,SpanIdandParentId, so every log line carries them. When my code calls another API withHttpClient, the handler addstraceparentautomatically, so the downstream service logs under the same trace id. Messages are the gap: they're asynchronous, so the trace context has to travel inside the message. The Azure Service Bus SDK writes it into the message's application properties; for a custom transport I use OpenTelemetry's propagator to inject and extract it.The mistake I see is teams inventing an
X-Correlation-IDheader with custom middleware, while the platform already propagates a trace id that Application Insights, Jaeger and Grafana understand. Then they have two ids that don't match. I use the trace id as the correlation id, return it inProblemDetailsso support can quote it, and put business identifiers in properties or baggage. One id, propagated by the platform, beats a home-made one every time."
| Piece | Scope | Set by | Carries |
|---|---|---|---|
| Log scope | One process, one async flow | BeginScope, hosting |
Any properties |
Activity |
One operation (span) | ASP.NET Core, HttpClient, SDKs, your code | TraceId, SpanId, tags, baggage |
traceparent header |
Between processes | HttpClient, gRPC, messaging SDKs | Trace id, parent span id, sampled flag |
baggage header |
Between processes | Your code | Small key/value pairs (tenant, region) |
| Business id | Domain | Your code | OrderId, PaymentId as properties |
| Transport | Automatic? | How |
|---|---|---|
| Incoming HTTP | Yes | Hosting reads traceparent |
HttpClient |
Yes | DiagnosticsHandler writes traceparent |
| gRPC | Yes | Same HTTP mechanism |
| Azure Service Bus / Event Hubs | Yes, in SDK | Diagnostic-Id / traceparent application property |
| RabbitMQ, custom queues, background jobs | No | Inject/extract with Propagators.DefaultTextMapPropagator |
Fire-and-forget Task.Run |
Partly | Activity flows via ExecutionContext, but the request may end first |
In a checkout flow spanning [four] services and a Service Bus queue, support used to search five log stores by timestamp. After switching to trace context end to end and returning traceId in error responses, a support ticket with a trace id led to the full transaction in Application Insights in under [a minute], down from about [20 minutes].
Checks whether the candidate can trace a request across services using the platform's built-in mechanisms rather than ad-hoc ids.
Green flags
BeginScope, its async flow and IncludeScopes.Activity, traceparent format and automatic HttpClient propagation.Red flags
ILogger.BeginScope<TState>(state) returns an IDisposable. The default LoggerFactoryScopeProvider keeps a linked stack of scopes in an AsyncLocal<Scope>. Providers that support scopes (ISupportExternalScope) walk the stack when writing a log. The console provider only prints them with IncludeScopes = true; OpenTelemetry includes them as attributes with IncludeScopes = true.
using (logger.BeginScope("{OrderId}", 42)) scope stack (AsyncLocal)
{ ββββββββββββββββββββββββββββββ
await repo.SaveAsync(); // logs here βββββΊ β OrderId = 42 β
} β SpanId, TraceId, ParentIdβ β ActivityTrackingOptions
β RequestId, RequestPath β β hosting scope
ββββββββββββββββββββββββββββββ
Passing a Dictionary<string, object> or a template with placeholders gives structured properties; passing a plain string gives one unnamed value.
System.Diagnostics.Activity represents a span. Activity.Current is stored in an AsyncLocal, so it flows across await. The W3C traceparent header looks like:
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
β β β β flags (01 = sampled)
β β β parent span id (8 bytes)
β β trace id (16 bytes)
β version
ASP.NET Core's hosting diagnostics create an activity per request, using the incoming header as parent when present. Since .NET 5 the default id format is W3C.
Browser βββΊ API Gateway βββΊ Orders API ββHttpClientβββΊ Pricing API
trace T, span A trace T, span B trace T, span C
β
βββ Service Bus message
(application property traceparent = T-B)
β
βΌ
Fulfilment worker: trace T, span D
All logs carry trace id T, so one query returns the whole transaction.
LoggerFactoryOptions.ActivityTrackingOptions decides which activity fields become scope properties: TraceId, SpanId, ParentId, TraceState, TraceFlags, Tags, Baggage. The Generic Host sets SpanId | TraceId | ParentId by default. You can add Baggage to log baggage items automatically.
For custom transports, inject the current context into message headers on send and extract it on receive:
Propagators.DefaultTextMapPropagator.Inject(new PropagationContext(Activity.Current!.Context, Baggage.Current), headers, setter);
then start a new Activity with the extracted parent context in the consumer. Hosted services have no ambient request, so start an activity per unit of work from your own ActivitySource.
Baggage propagates key/value pairs to every downstream call, including third parties if you're careless. Keep it small and never put personal data or secrets in it.
IncludeScopes on the JSON console and log inside a BeginScope; inspect the Scopes array.HttpClient and compare the TraceId in both apps' logs.traceparent header via curl and confirm the API logs that trace id.Diagnostic-Id application property in Service Bus Explorer.Task.Run without awaiting and log inside it after the request has finished; observe which scope values remain.Business scope in a handler, trace id returned to clients, and manual propagation for a custom queue.
// Program.cs
using System.Diagnostics;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.AddJsonConsole(o => o.IncludeScopes = true);
// Include baggage in log scopes as well as TraceId/SpanId/ParentId
builder.Logging.Configure(o => o.ActivityTrackingOptions =
ActivityTrackingOptions.TraceId | ActivityTrackingOptions.SpanId |
ActivityTrackingOptions.ParentId | ActivityTrackingOptions.Baggage);
builder.Services.AddHttpClient<PricingClient>(c => c.BaseAddress = new Uri("https://pricing.internal"));
// Put the trace id into every ProblemDetails response so support can find the logs
builder.Services.AddProblemDetails(o => o.CustomizeProblemDetails = ctx =>
ctx.ProblemDetails.Extensions["traceId"] = Activity.Current?.TraceId.ToString() ?? ctx.HttpContext.TraceIdentifier);
var app = builder.Build();
app.UseExceptionHandler();
app.MapPost("/orders/{orderId:guid}/price", async (Guid orderId, PricingClient pricing, ILogger<Program> logger, CancellationToken ct) =>
{
// Every log inside this block, in any class, gets OrderId
using var _ = logger.BeginScope(new Dictionary<string, object> { ["OrderId"] = orderId });
logger.LogInformation("Pricing order");
var total = await pricing.GetTotalAsync(orderId, ct); // HttpClient adds traceparent automatically
logger.LogInformation("Order priced at {Total}", total);
return TypedResults.Ok(total);
});
app.Run();
public sealed class PricingClient(HttpClient http)
{
public async Task<decimal> GetTotalAsync(Guid orderId, CancellationToken ct) =>
await http.GetFromJsonAsync<decimal>($"/totals/{orderId}", ct);
}
Propagating through a transport the SDKs don't cover (package OpenTelemetry.Api):
using System.Diagnostics;
using OpenTelemetry;
using OpenTelemetry.Context.Propagation;
public static class QueueTracing
{
private static readonly ActivitySource Source = new("Shop.Queue");
private static readonly TextMapPropagator Propagator = Propagators.DefaultTextMapPropagator;
// Producer: copy traceparent/tracestate/baggage into message headers
public static void Inject(IDictionary<string, string> headers) =>
Propagator.Inject(new PropagationContext(Activity.Current?.Context ?? default, Baggage.Current),
headers, static (h, key, value) => h[key] = value);
// Consumer: continue the producer's trace
public static Activity? StartProcessing(IReadOnlyDictionary<string, string> headers)
{
var parent = Propagator.Extract(default, headers,
static (h, key) => h.TryGetValue(key, out var v) ? [v] : []);
Baggage.Current = parent.Baggage;
return Source.StartActivity("process message", ActivityKind.Consumer, parent.ActivityContext);
}
}
X-Correlation-ID header and middleware. Why it is wrong: It duplicates the trace id, doesn't interoperate with tracing tools, and often isn't propagated by every client. Instead: Use W3C Trace Context and the trace id.BeginScope with a plain interpolated string. Why it is wrong: You get one unnamed value instead of queryable properties. Instead: Use a dictionary or a template with placeholders.IncludeScopes = true. Instead: Enable scopes on the providers that should record them.using). Why it is wrong: The properties leak into unrelated later logs on that async flow. Instead: Always use using or using var.traceId in ProblemDetails.Correlation is a platform concern: if every team builds its own, nothing lines up. I standardise on W3C Trace Context and OpenTelemetry, verify propagation at every hop that isn't plain HTTP (queues, scheduled jobs, third-party webhooks), and use scopes only for business context. The test I use is simple: pick a random error from yesterday and see whether one query, keyed on its trace id, shows every service it touched.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Trace id as correlation id | Any HTTP/gRPC/messaging system | Needs propagation at custom hops | β |
| Log scopes with business ids | Group logs by order, tenant, job | IncludeScopes, disposal discipline |
Data that should be on the trace as tags |
| Baggage | Small values needed downstream | Sent everywhere, size limits | Personal data, large values |
| Custom correlation header | Legacy partner that can't send traceparent | Two ids to map | New systems |
Thread-local storage gives each thread its own copy of a value. [ThreadStatic] marks a static field as per-thread (fast, but the field initialiser runs only once, so other threads see the default). ThreadLocal<T> adds a per-thread factory, optional tracking of all values and Dispose. Both are tied to the thread, so they break across await, where the continuation may run on another thread. AsyncLocal<T> is tied to the logical async flow instead: it is stored in the ExecutionContext and flows into awaited continuations and Task.Run, which is how Activity.Current and logging scopes work.
In ASP.NET Core, register AddProblemDetails(), one or more IExceptionHandler implementations (.NET 8+) with AddExceptionHandler<T>(), and app.UseExceptionHandler() early in the pipeline. Handlers log once and map known exceptions to the right status code and an RFC 9457 ProblemDetails body, and never leak stack traces in production. For the process as a whole, AppDomain.CurrentDomain.UnhandledException is a last-chance notification: you can log and flush, but the process still terminates. TaskScheduler.UnobservedTaskException fires when a faulted task that nobody awaited is garbage-collected; it does not crash the process by default. In a BackgroundService, an unhandled exception in ExecuteAsync stops the host by default (.NET 6+). async void exceptions go to the synchronisation context and usually crash the process, so avoid async void except for event handlers.
OpenTelemetry gives you three correlated signals: traces (a span per operation, linked by trace id), metrics (cheap aggregated counters and histograms) and logs (events that carry the TraceId and SpanId of the span they were written in).
In .NET the runtime already emits Activity and Meter data; you call AddOpenTelemetry() with WithTracing, WithMetrics and WithLogging, set a resource (service.name), and choose an exporter: UseOtlpExporter() for any OTLP back end or Collector (endpoint from OTEL_EXPORTER_OTLP_ENDPOINT or options), or the Azure Monitor distro (UseAzureMonitor()) for Application Insights.
For cost: metrics for rates and latency (never sampled), sampled traces (the distro now defaults to a rate-limited sampler of 5 traces per second, which adapts the kept percentage to load; you can change the rate or switch to a fixed SamplingRatio), level-filtered logs, and tail sampling in a Collector, configured with policies to keep errors and slow traces. The trade-off is completeness versus ingestion cost.
How to tell it (STAR)
**S:** At [company] customers reported paid orders that never shipped, about [30] a week, and nobody could follow an order from the checkout API into the fulfilment worker. **T:** I had to find where the orders went and make that kind of problem traceable in future. **A:** I saw in Application Insights that the API and worker traces weren't connected, confirmed the queue messages had no traceparent header, and added an order-id scope to the worker, which showed the missing orders failing deserialisation after a contract change. We replayed them, then I added trace propagation through the queue with the OpenTelemetry propagator and a test that checks the trace id survives the hop. **R:** Lost orders went to [zero], and support can now go from an order's trace id to every log across both services in [under a minute].
Last updated 23 Nov 2026.