Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion tensormap-backend/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

from app.config import get_settings
from app.exceptions import AppException, app_exception_handler, generic_exception_handler
from app.middleware import RequestLoggingMiddleware
from app.middleware import RequestIDMiddleware, RequestLoggingMiddleware
from app.routers import data_process, data_upload, deep_learning, project
from app.shared.logging_config import get_logger
from app.socketio_instance import sio
Expand Down Expand Up @@ -43,6 +43,7 @@ async def lifespan(app: FastAPI):
allow_methods=["*"],
allow_headers=["*"],
)
app.add_middleware(RequestIDMiddleware)
app.add_middleware(RequestLoggingMiddleware)

app.add_exception_handler(AppException, app_exception_handler)
Expand Down
18 changes: 17 additions & 1 deletion tensormap-backend/app/middleware.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"""HTTP request/response logging middleware."""
"""HTTP request/response logging and tracing middleware."""

import re
import time
import uuid

from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
Expand All @@ -22,6 +23,21 @@ def _sanitize_path(path: str) -> str:
return path


class RequestIDMiddleware(BaseHTTPMiddleware):
"""Add a unique request ID to each request for tracing."""

async def dispatch(self, request: Request, call_next) -> Response:
request_id = request.headers.get("X-Request-ID")
if not request_id:
request_id = str(uuid.uuid4())

request.state.request_id = request_id
response = await call_next(request)
response.headers["X-Request-ID"] = request_id

return response


class RequestLoggingMiddleware(BaseHTTPMiddleware):
"""Log method, path, status code, and duration for every HTTP request."""

Expand Down
Loading