Skip to content

Commit

Permalink
Flask logging a request id round 2
Browse files Browse the repository at this point in the history
  • Loading branch information
k-macmillan committed Nov 29, 2024
1 parent 5ab78d9 commit 93f7f99
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 deletions notifications_utils/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

0 comments on commit 93f7f99

Please sign in to comment.