Skip to main content

PyPI - Downloads PyPI - License PyPI - Version PyPI - Python Version PyPI - Status Dependencies Last Commit

asgi-request-id 🌟

asgi-request-id is a middleware for ASGI applications that provides a unique request identifier for each incoming request. This identifier can be used for logging, tracing, and debugging purposes, making it easier to track requests as they flow through your application. The middleware is highly configurable, allowing you to customize the request ID generation, specify headers for incoming and outgoing request IDs, and exclude certain paths from request ID handling. It is compatible with popular ASGI frameworks like Starlette and FastAPI, and can be easily integrated into your existing application with minimal changes.

Table of Contents 📚

Installation 📦

pip install asgi-request-id

Usage 🚀

The asgi-request-id middleware performs the following actions:

  • Searches for an incoming request identifier using the incoming_request_id_header attribute and uses it as the request ID if found.
  • Generates a unique request ID with an optional prefix if no incoming request identifier is found.
  • Stores the request ID in a context variable, making it accessible to the logging context through a filter.
  • Includes the request ID in the response headers. If the outgoing_request_id_header attribute is set, its value will be used as the response header name. Ensure that the chosen header name complies with HTTP header naming conventions.

For Python 3.6 compatibility, install the backported contextvars package.

Middleware 🛠️

The RequestIdMiddleware class is used to handle the request ID header. It has the following attributes:

  • app: The ASGI application.
  • excluded_paths: List of paths to exclude from middleware processing.
  • incoming_request_id_header: Optional incoming request ID header.
  • outgoing_request_id_header: Optional outgoing request ID header.
  • prefix: Optional prefix to add to the request ID.
  • skip_validate_header_name: Optional flag to skip header name validation.
  • uuid_generator: Optional UUID generator.

Example 🔍

Here is a minimal example demonstrating how to use the asgi-request-id middleware. Additional examples with more detailed use cases and configurations can be found in the examples folder of the repository.

import os
import uvicorn
from asgi_request_id import RequestIdMiddleware
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Route
from uuid import uuid4

async def info_endpoint(request: Request) -> JSONResponse:
    return JSONResponse({"message": "info"})

async def excluded_endpoint(request: Request) -> JSONResponse:
    return JSONResponse({"message": "excluded"})

routes = [
    Route("/info", info_endpoint, methods=["GET"]),
    Route("/excluded", excluded_endpoint, methods=["GET"]),
]

app = Starlette(routes=routes)
app.add_middleware(
    RequestIdMiddleware,
    excluded_paths=["/excluded"],
    incoming_request_id_header="x-request-id",
    outgoing_request_id_header="x-request-id",
    prefix="my-special-prefix-",
    uuid_generator=lambda: uuid4().hex,
)

if __name__ == "__main__":
    log_config = f"{os.path.dirname(__file__)}{os.sep}conf{os.sep}logging.yaml"
    config = uvicorn.Config("app:app", host="127.0.0.1", port=8000, log_config=log_config)
    server = uvicorn.Server(config)
    server.run()

Logging 📝

To integrate the request ID into your logging, you can use the RequestIdFilter class. Here is an example logging.yaml configuration:

---
version: 1
filters:
  request_id:
    (): 'asgi_request_id.RequestIdFilter'
    default_value: '-'
formatters:
  default:
    (): 'uvicorn.logging.DefaultFormatter'
    fmt: '%(levelprefix)s [%(asctime)s] %(message)s'
  access:
    (): 'uvicorn.logging.AccessFormatter'
    fmt: '%(levelprefix)s [%(asctime)s] {%(request_id)s} %(client_addr)s - "%(request_line)s" %(status_code)s'
handlers:
  default:
    class: logging.StreamHandler
    formatter: default
    stream: ext://sys.stderr
  access:
    class: logging.StreamHandler
    filters: [request_id]
    formatter: access
    stream: ext://sys.stdout
loggers:
  uvicorn:
    level: INFO
    handlers:
    - default
  uvicorn.error:
    level: INFO
  uvicorn.access:
    level: INFO
    propagate: False
    handlers:
    - access

Metadata

Release files for asgi-request-id 1.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for asgi-request-id 1.0.1
File Size Uploaded
asgi_request_id-1.0.1.tar.gz 6.4 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for asgi-request-id 1.0.1
File Interpreter ABI Platform
asgi_request_id-1.0.1-py3-none-any.whl Python 3 none any Details

Total release size: 15.0 kB

Release files / asgi_request_id-1.0.1.tar.gz

Download URL asgi_request_id-1.0.1.tar.gz
Size 6.4 kB
Tags Source
SHA-256 checksum
How to use checksums
5a8c30b6062b497454d58b642fb661090e2dec8cec7b944fd2c5d591c34198e0
BLAKE2b-256 checksum
How to use checksums
fb9cdd2ee49d3644256be8e0e48e4613cd089ba0a2583d514f85c37a989c26eb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.2.1 CPython/3.13.7 Darwin/24.5.0

Release files / asgi_request_id-1.0.1-py3-none-any.whl

Download URL asgi_request_id-1.0.1-py3-none-any.whl
Size 8.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e33fdc8334e3e2ae6180779478314a428a6b7fbdf1632efeef6d504fae47dd7d
BLAKE2b-256 checksum
How to use checksums
ddd148edf417b1d779cbf210092f8f9659f610aeaca0ff7a86822a701a754644
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.2.1 CPython/3.13.7 Darwin/24.5.0

Release history Release notifications | RSS feed

This release

1.0.1 This release

2 release files

1.0.0

2 release files

0.2.1

2 release files

0.2.0

2 release files

0.1.2

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page