correlation¶
- class litestar.middleware.correlation.CorrelationMiddleware[source]¶
Bases:
ASGIMiddlewareASGI 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_lengthis not positive or both header name options are provided.
- 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
Noneif none was set.