Skip to content

[FastAPI] Add request ID middleware for log correlation — Hermes Agent#1

Open
nporter-codes wants to merge 2 commits into
mainfrom
feature/request-id-middleware
Open

[FastAPI] Add request ID middleware for log correlation — Hermes Agent#1
nporter-codes wants to merge 2 commits into
mainfrom
feature/request-id-middleware

Conversation

@nporter-codes
Copy link
Copy Markdown
Owner

Summary

Adds a RequestIDMiddleware for FastAPI that generates a UUID request ID per request, stores it in request.state, echoes client-provided X-Request-ID headers, and plumbs the ID into log records.

Changes

  • New file: fastapi/fastapi/middleware/request_id.py
    • RequestIDMiddleware — Starlette BaseHTTPMiddleware subclass
    • RequestIDFilter — logging filter that injects request_id into every log record
    • request_id_context — module-level dict context for the filter
    • Auto-installs the filter on the fastapi logger at import time

Acceptance Criteria Covered

  • Each request gets a unique UUID in X-Request-ID response header
  • Client-provided X-Request-ID is preserved and echoed back
  • Log entries during the request include the request ID
  • Request IDs do not leak between concurrent requests (context var cleared in finally)
  • Existing logger behavior works when middleware is not applied

Agent Info

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant