AsyncLocal Serilog LogContext in Blazor Server Middleware

Viewed 37

I create a custom Middliware to Push info about HttpContext into my Serilog LogContext:

if (context == null) throw new ArgumentNullException(nameof(context));

string profile = context.Request.Host.Host;
string ipAddress = context.Connection.RemoteIpAddress?.ToString();
string userAgent = context.Request.Headers["User-Agent"].ToString();

using (LogContext.PushProperty("Profile", profile))
using (LogContext.PushProperty("IpAddress", ipAddress))
using (LogContext.PushProperty("UserAgent", userAgent))
{
  await _next(context);
}

I want to understand the behavior of my LogContext properties in various queries (Hhtp Requests).

From Microsoft Docs:

AsyncLocal Represents ambient data that is local to a given asynchronous control flow, such as an asynchronous method.

What is my asynchronous control flow in Blazor Server Middleware?

1 Answers

What is my asynchronous control flow

The AsyncLocal<T> values persist for the entirety of await _next(context); i.e., until _next completes. In all modern middleware systems, this is all the middleware following the current one.

Related