From 39cddca1f1c5b6ed8ac03121d1c5975fadd24dc4 Mon Sep 17 00:00:00 2001 From: Petr Messner Date: Thu, 2 May 2024 11:17:05 +0200 Subject: [PATCH] RequestIdContextAccessLogger: do not fail when request_id is not set --- aiohttp_request_id_logging/__init__.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/aiohttp_request_id_logging/__init__.py b/aiohttp_request_id_logging/__init__.py index fc097e3..da9a675 100644 --- a/aiohttp_request_id_logging/__init__.py +++ b/aiohttp_request_id_logging/__init__.py @@ -48,7 +48,16 @@ def new_factory(*args, **kwargs): class RequestIdContextAccessLogger (_AccessLogger): def log(self, request, response, time): - token = request_id.set(request['request_id']) + try: + request_id_value = request['request_id'] + except KeyError: + # If there is no request['request_id'], for example when an error + # occurs in a middleware, fall back to just logging without setting + # the request_id context variable. + super().log(request, response, time) + return + + token = request_id.set(request_id_value) try: super().log(request, response, time) finally: