{"id":2867,"library":"asgi-correlation-id","title":"ASGI Correlation ID Middleware","description":"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.","status":"active","version":"4.3.4","language":"en","source_language":"en","source_url":"https://github.com/snok/asgi-correlation-id","tags":["asgi","middleware","logging","correlation-id","fastapi","starlette","tracing","observability"],"install":[{"cmd":"pip install asgi-correlation-id","lang":"bash","label":"Core library"},{"cmd":"pip install asgi-correlation-id[uvicorn]","lang":"bash","label":"With Uvicorn access logging integration"},{"cmd":"pip install asgi-correlation-id[sentry]","lang":"bash","label":"With Sentry integration"}],"dependencies":[{"reason":"Used for internal version comparisons, particularly in Sentry integration.","package":"packaging","optional":false},{"reason":"Optional dependency for Uvicorn-specific access logging setup.","package":"uvicorn","optional":true},{"reason":"Optional dependency for Sentry integration to propagate correlation IDs.","package":"sentry-sdk","optional":true}],"imports":[{"symbol":"CorrelationIdMiddleware","correct":"from asgi_correlation_id import CorrelationIdMiddleware"},{"note":"A `contextvars.ContextVar` holding the current request's correlation ID.","symbol":"correlation_id","correct":"from asgi_correlation_id import correlation_id"},{"note":"A logging filter to automatically inject the correlation ID into log records.","symbol":"correlation_id_filter","correct":"from asgi_correlation_id import correlation_id_filter"}],"quickstart":{"code":"import logging\nfrom fastapi import FastAPI\nfrom asgi_correlation_id import CorrelationIdMiddleware, correlation_id, correlation_id_filter\n\n# Configure standard Python logging to include correlation ID\n# This adds the 'correlation_id' attribute to log records\nlogging.basicConfig(level=logging.INFO, format='%(levelname)s: %(asctime)s - %(correlation_id)s - %(message)s')\nlogging.getLogger('your_app_logger').addFilter(correlation_id_filter)\n# Note: For uvicorn's access logs, you need to configure uvicorn's log_config separately,\n# e.g., uvicorn.run(app, log_config={'format': '%(levelprefix)s %(asctime)s - %(correlation_id)s - %(message)s'})\n\napp = FastAPI()\n\n# Add the CorrelationIdMiddleware to your ASGI application\napp.add_middleware(\n    CorrelationIdMiddleware,\n    # You can customize the header name, default is 'X-Request-ID'\n    # header_name=\"X-Correlation-ID\",\n    # Optionally, generate UUIDv4 if no header is present (default True)\n    # generate_uuid_if_not_found=True\n)\n\n@app.get(\"/items/{item_id}\")\nasync def read_item(item_id: int):\n    # The correlation ID is automatically available in logs configured with the filter\n    logging.getLogger('your_app_logger').info(f\"Processing request for item {item_id}\")\n\n    # You can also access the correlation ID directly within your code\n    current_correlation_id = correlation_id.get()\n    logging.getLogger('your_app_logger').info(f\"Correlation ID retrieved directly: {current_correlation_id}\")\n    \n    return {\"item_id\": item_id, \"correlation_id\": current_correlation_id}\n\nif __name__ == '__main__':\n    # To run this application:\n    # 1. Save this code as 'main.py'\n    # 2. Run from your terminal: 'uvicorn main:app --port 8000'\n    # Then access http://localhost:8000/items/123\n    print(\"To run: save as main.py and execute 'uvicorn main:app --port 8000'\")\n","lang":"python","description":"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()`."},"warnings":[{"fix":"Manually add the correlation ID header name (e.g., `X-Request-ID`) to `Access-Control-Expose-Headers` in your ASGI CORS middleware (e.g., `CORSMiddleware` in Starlette/FastAPI).","message":"Version 4.0.0 removed the `Access-Control-Expose-Headers` response header by default. If your frontend relies on this header for fetching the correlation ID, you must explicitly configure your CORS middleware to expose `X-Request-ID` or your custom correlation ID header.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Review your `CorrelationIdMiddleware` initialization. If specific behavior regarding incoming header updates or response header values is required, explicitly set `update_request_header=True` or `False` as needed.","message":"In version 4.0.0, the default value of the `update_request_header` parameter in `CorrelationIdMiddleware` changed. This might affect how incoming `X-Request-ID` headers are handled and whether the response header reflects the *generated* or *incoming* ID.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Upgrade your Python environment to 3.8 or newer to ensure continued compatibility and receive ongoing support and updates.","message":"Official support for Python 3.7 was dropped in version 4.3.0. While the middleware might still function on 3.7 for now, future compatibility is not guaranteed.","severity":"deprecated","affected_versions":">=4.3.0"},{"fix":"Use the `uvicorn` extra (`pip install asgi-correlation-id[uvicorn]`) and configure Uvicorn's `log_config` or `log_format` with a custom format string that includes `%(correlation_id)s` (e.g., `--log-config uvicorn_log_config.json` or `uvicorn.run(..., log_config={'format': '...'}`).","message":"Integrating the correlation ID into Uvicorn's default access logs requires explicit configuration. It is not automatically included in the default `uvicorn.run()` log format.","severity":"gotcha","affected_versions":"*"},{"fix":"Update `asgi-correlation-id` to version 4.3.3 or newer if you are using `sentry-sdk` 2.x to avoid potential deprecation warnings and ensure proper integration.","message":"When integrating `asgi-correlation-id` with Sentry, ensure your `sentry-sdk` version is compatible. Version 4.3.3 of `asgi-correlation-id` specifically fixed deprecation warnings that could occur with `sentry-sdk` 2.x.","severity":"gotcha","affected_versions":"<4.3.3 (when using sentry-sdk 2.x)"}],"env_vars":null,"last_verified":"2026-04-11T00:00:00.000Z","next_check":"2026-07-10T00:00:00.000Z"}