import logging import time from fastapi import Request from starlette.middleware.base import BaseHTTPMiddleware # Configure logging logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" ) logger = logging.getLogger("todo_app") class RequestLoggingMiddleware(BaseHTTPMiddleware): """Middleware to log incoming HTTP requests""" async def dispatch(self, request: Request, call_next): # Log the incoming request start_time = time.time() logger.info( f"Incoming request: {request.method} {request.url.path}" ) # Process the request response = await call_next(request) # Calculate processing time process_time = time.time() - start_time # Log the response logger.info( f"Request completed: {request.method} {request.url.path} - " f"Status: {response.status_code} - Time: {process_time:.4f}s" ) return response