import sys import uuid import time import loguru from starlette.middleware.base import BaseHTTPMiddleware logger = loguru.logger logger.remove() logger.add( sys.stdout, format="{time} - {level} - {file.path} - {function} - {line} - ({extra[request_id]}) :: {message}", level="DEBUG", backtrace=False, ) class RequestLoggingMiddleware(BaseHTTPMiddleware): """Middleware for logging incoming HTTP requests and their responses. Attributes: app: The ASGI application to which the middleware is applied. Methods: dispatch: Method to intercept and handle HTTP requests. It logs the start of the request, executes the subsequent middleware and the ASGI application, logs any exceptions that occur during the processing of the request, and logs the end of the request. """ def __init__(self, app): super().__init__(app) async def dispatch(self, request, call_next): request_id = str(uuid.uuid4()) with logger.contextualize(request_id=request_id): logger.info("Request started") try: return await call_next(request) except Exception as ex: logger.exception(f"Request failed: {ex}") finally: logger.info("Request ended")