correlation

class litestar.middleware.correlation.CorrelationMiddleware[source]

Bases: ASGIMiddleware

ASGI middleware for extracting, generating, and propagating correlation IDs.

The active correlation ID is stored on the connection scope and can be retrieved with get_correlation_id().

scopes: tuple[ScopeType, ...] = (ScopeType.HTTP, ScopeType.WEBSOCKET)

Scope types this middleware should be applied to

__init__(header_names: Sequence[str] | None = None, additional_header_names: Sequence[str] | None = None, response_header_name: str | None = 'x-request-id', max_length: int = 128) None[source]

Initialize CorrelationMiddleware.

Parameters:
  • header_names – Header name or sequence of header names to inspect in priority order, replacing the defaults.

  • additional_header_names – Header name or sequence of header names to inspect after the defaults.

  • response_header_name – Optional header name to echo correlation ID in response. Set to None to disable.

  • max_length – Maximum length for correlation IDs to prevent log injection.

Raises:

ValueError – If max_length is not positive or both header name options are provided.

async handle(scope: Scope, receive: Receive, send: Send, next_app: ASGIApp) None[source]

ASGI call handler.

Parameters:
  • scope – The ASGI scope.

  • receive – The ASGI receive callable.

  • send – The ASGI send callable.

  • next_app – The next ASGI application in the middleware stack.

litestar.middleware.correlation.get_correlation_id(connection: ASGIConnection[Any, Any, Any, Any] | Scope) str | None[source]

Get the correlation ID stored on the connection scope by CorrelationMiddleware.

Parameters:

connection – An ASGI connection or scope.

Returns:

The correlation ID, or None if none was set.