From 93f7f998c5787a5655d8764f64f586d6933e366f Mon Sep 17 00:00:00 2001 From: Kyle MacMillan Date: Fri, 29 Nov 2024 15:11:23 -0500 Subject: [PATCH] Flask logging a request id round 2 --- notifications_utils/logging.py | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/notifications_utils/logging.py b/notifications_utils/logging.py index 5ceadaa9..1acfd707 100644 --- a/notifications_utils/logging.py +++ b/notifications_utils/logging.py @@ -4,6 +4,7 @@ from itertools import product from pathlib import Path from time import monotonic +from uuid import uuid4 from flask import request, g from flask.ctx import has_request_context @@ -152,13 +153,16 @@ def filter(self, record): class RequestIdFilter(logging.Filter): - @property - def request_id(self): - if has_request_context() and hasattr(request, 'request_id'): - return request.request_id - - return 'no-request-id' - def filter(self, record): - record.requestId = self.request_id + # The else is for celery + record.requestId = RequestIdFilter._get_req_id() if has_request_context() else '' return record + + @classmethod + def _get_req_id(self): + # Guard for this request: + if getattr(g, 'request_id', ''): + return g.request_id + + g.request_id = str(uuid4()).replace('-', '') + return g.request_id