Building the logging middleware
The core component of this centralized application log is the custom middleware that we must implement in the main.py
component where we set up Loguru. FastAPI’s mount allows us to centralize some cross-cutting concerns such as logging without adding anything to the sub-applications. One middleware implementation in the main.py
component of the top-level application is good enough to pursue logging across the independent microservices. The following is the middleware implementation for our specimen application:
@app.middleware("http") async def log_middleware(request:Request, call_next): log_id = str(uuid4()) with logger.contextualize(log_id=log_id): logger.info('Request to access ' + request.url.path) try...