1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-03 01:16:10 +00:00

feat(logs): each log line names its request, user and client address

A request gets nginx's $request_id (or a new one when it comes without a
valid one) and sends it back in X-Request-ID. The app log's lines carry
the logger, process and thread, the request ID, the signed-in user and the
client address; gunicorn's access lines carry the client address from
X-Real-IP and the same request ID, so the two logs can be joined.
This commit is contained in:
catborise 2026-11-05 14:36:58 +03:00
parent b5ed197568
commit 26ca363b0e
6 changed files with 95 additions and 2 deletions

View file

@ -0,0 +1,24 @@
"""Each log line of a web request names the request, its user and its client
address (set by webvirtcloud.middleware.RequestIdMiddleware)."""
import contextvars
import logging
current_request = contextvars.ContextVar("current_request", default=None)
class RequestFilter(logging.Filter):
"""Adds request_id, user and ip to each record; "-" outside a web request."""
def filter(self, record):
request = current_request.get()
record.request_id = getattr(request, "request_id", "-")
record.ip = getattr(request, "client_ip", None) or "-"
record.user = "-"
try:
user = getattr(request, "user", None)
if user is not None and user.is_authenticated:
record.user = user.get_username()
except Exception: # the user may be read from the database here; a failure must not lose the line
pass
return True