File size: 1,331 Bytes
79b7942
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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")