snok / asgi-correlation-id

Request ID propagation for ASGI apps
MIT License
370 stars 29 forks source link

Using it in a middleware #35

Closed ccrvlh closed 2 years ago

ccrvlh commented 2 years ago

Hi, I have a middleware in place that logs requests, response time, etc, something like:


    @app.middleware("http")
    async def log_requests(request: Request, call_next):
        logger.info(f"Request: {request.method} {request.url.path}")
        start_time = time.time()
        response = await call_next(request)
        process_time = (time.time() - start_time) * 1000
        formatted_process_time = '{0:.2f}'.format(process_time)
        logger.info(f"Finished request in {formatted_process_time}ms with status: {response.status_code}")
        return response

After configuring the correlation id, I can see it working when using logger.info("Route") inside the route, but the middleware above won't log the ID. Is there a way to make it available in other middleware?

Thanks a lot!

sondrelg commented 2 years ago

Middleware are evaluated in sequence (first defined is called first on the way in, and last on the way out). If you want correlation IDs in your middleware logs, you should make sure to put this middleware first 🙂

Let me know if you have any trouble 👍

ccrvlh commented 2 years ago

Perfect, thanks a lot! I added the (correlation-id) middleware and it works perfectly. Thanks!