import json import time from fastapi import Request, Response from starlette.middleware.base import BaseHTTPMiddleware from src.core.log_conf import logger class RequestLoggingMiddleware(BaseHTTPMiddleware): async def dispatch(self, request: Request, call_next) -> Response: start_time = time.time() path = request.url.path if path != "/health": # Log request info request_info ={ "method": request.method, "path": path, "client_ip": request.client.host if request.client else "unknown" } logger.info("Incoming: %s", json.dumps(request_info)) # Process request response = await call_next(request) if path != "/health": # Log response info duration_ms = (time.time()- start_time)*1000 response_info = { "status_code": response.status_code, "duration_ms": round(duration_ms, 2) } logger.info("completed: %s", json.dumps(response_info)) return response