ASGI Correlation ID Middleware

4.3.4 · active · verified Sat Apr 11

asgi-correlation-id is an ASGI middleware that assigns a unique correlation ID (e.g., X-Request-ID) to each incoming request, making it easier to trace logs across services and requests in ASGI applications like FastAPI or Starlette. The current version is 4.3.4, and the library maintains an active release cadence with frequent minor updates and bug fixes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to integrate `asgi-correlation-id` with a FastAPI application. It shows how to add the `CorrelationIdMiddleware` and configure standard Python logging with `correlation_id_filter` to automatically include the correlation ID in log records. It also illustrates how to access the current request's correlation ID directly using `correlation_id.get()`.

import logging
from fastapi import FastAPI
from asgi_correlation_id import CorrelationIdMiddleware, correlation_id, correlation_id_filter

# Configure standard Python logging to include correlation ID
# This adds the 'correlation_id' attribute to log records
logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(asctime)s - %(correlation_id)s - %(message)s')
logging.getLogger('your_app_logger').addFilter(correlation_id_filter)
# Note: For uvicorn's access logs, you need to configure uvicorn's log_config separately,
# e.g., uvicorn.run(app, log_config={'format': '%(levelprefix)s %(asctime)s - %(correlation_id)s - %(message)s'})

app = FastAPI()

# Add the CorrelationIdMiddleware to your ASGI application
app.add_middleware(
    CorrelationIdMiddleware,
    # You can customize the header name, default is 'X-Request-ID'
    # header_name="X-Correlation-ID",
    # Optionally, generate UUIDv4 if no header is present (default True)
    # generate_uuid_if_not_found=True
)

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    # The correlation ID is automatically available in logs configured with the filter
    logging.getLogger('your_app_logger').info(f"Processing request for item {item_id}")

    # You can also access the correlation ID directly within your code
    current_correlation_id = correlation_id.get()
    logging.getLogger('your_app_logger').info(f"Correlation ID retrieved directly: {current_correlation_id}")
    
    return {"item_id": item_id, "correlation_id": current_correlation_id}

if __name__ == '__main__':
    # To run this application:
    # 1. Save this code as 'main.py'
    # 2. Run from your terminal: 'uvicorn main:app --port 8000'
    # Then access http://localhost:8000/items/123
    print("To run: save as main.py and execute 'uvicorn main:app --port 8000'")

view raw JSON →