""" Logging Middleware This module provides custom logging middleware for FastAPI requests to ensure consistent logging format with application logs. """ import time from typing import Callable from fastapi import Request, Response from starlette.middleware.base import BaseHTTPMiddleware from services.logging_config import get_request_logger logger = get_request_logger() class LoggingMiddleware(BaseHTTPMiddleware): """Custom logging middleware for unified request logging.""" async def dispatch(self, request: Request, call_next: Callable) -> Response: """ Log each request with unified formatting. Args: request: The incoming request call_next: The next middleware/handler in the chain Returns: The response """ # Start timing start_time = time.time() # Extract request information method = request.method url_path = request.url.path client_ip = request.client.host if request.client else "unknown" user_agent = request.headers.get("user-agent", "unknown") # Log request start logger.info(f"Request started: {method} {url_path} from {client_ip} " f"(User-Agent: {user_agent})") try: # Process the request response = await call_next(request) # Calculate processing time process_time = time.time() - start_time # Log successful response logger.info(f"Request completed: {method} {url_path} -> " f"{response.status_code} in {process_time:.3f}s") return response except Exception as e: # Calculate processing time for failed requests process_time = time.time() - start_time # Log error logger.error(f"Request failed: {method} {url_path} -> " f"Exception: {str(e)} in {process_time:.3f}s") # Re-raise the exception raise