Skip to content

[ FastAPI ] Add request ID middleware for log correlation#7231

Closed
dacdoyx wants to merge 2 commits into
UnsafeLabs:mainfrom
dacdoyx:fix/request-id-middleware
Closed

[ FastAPI ] Add request ID middleware for log correlation#7231
dacdoyx wants to merge 2 commits into
UnsafeLabs:mainfrom
dacdoyx:fix/request-id-middleware

Conversation

@dacdoyx

@dacdoyx dacdoyx commented Jun 26, 2026

Copy link
Copy Markdown

Summary

Implements #797 - Add request ID middleware to FastAPI.

Changes

  1. **New file: **

    • class extending
    • Reads header or generates a UUID
    • Stores request ID in
    • Sets request ID in ContextVar for access in loggers
    • Adds response header
    • Properly cleans up ContextVar after request
  2. **Updated: **

    • Added logging filter that injects into log records
    • Configured formatter with placeholder for log correlation
  3. **Updated: **

    • Exports and for public API

Usage

from fastapi import FastAPI
from fastapi.middleware import RequestIDMiddleware

app = FastAPI()
app.add_middleware(RequestIDMiddleware)

All log messages from the logger will now include the request ID:

2026-06-26 04:30:00 INFO [abc123def456] fastapi: Request processed

Closes #797

@github-actions

Copy link
Copy Markdown
Contributor

Unfortunately the changes in this PR didn't fully resolve the issue. Please rework your solution and submit a new pull request.

Make sure to review the acceptance criteria in the linked issue and verify all conditions are met before resubmitting. See CONTRIBUTING.md for guidelines.

@github-actions github-actions Bot closed this Jun 26, 2026
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.

[ FastAPI ] Add request ID middleware for log correlation

1 participant