kanban-app/backend/gunicorn_logger.py
2026-08-09 21:16:19 +03:00

29 lines
No EOL
1,005 B
Python

"""Custom Gunicorn logger.
Overrides the default timestamp atom `%(t)s` in access logs from Gunicorn's
default format `[09/Aug/2026:17:42:48 +0000]` to an ISO-like local-time format
`[2026-08-09 20:41:00 +0300]`, honoring the TZ environment variable.
"""
import os
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
from gunicorn.glogging import Logger
TIMEZONE = os.environ.get("TZ", "UTC")
class CustomLogger(Logger):
"""Gunicorn logger that emits timezone-aware ISO timestamps."""
def atoms(self, resp, req, environ, request_time):
"""Build the log atoms, overriding the time atom with a custom format."""
atoms = super().atoms(resp, req, environ, request_time)
try:
now = datetime.now(ZoneInfo(TIMEZONE))
except Exception:
now = datetime.now(timezone.utc)
# [09/Aug/2026:17:42:48 +0000] -> [2026-08-09 20:41:00 +0300]
atoms["t"] = f"[{now.strftime('%Y-%m-%d %H:%M:%S %z')}]"
return atoms