Files
mtusi2026lab6/app/observability/logging.py
T

53 lines
2.0 KiB
Python

from __future__ import annotations
import json
import logging
from datetime import datetime, timezone
from opentelemetry import trace
_STANDARD_FIELDS = {
'args', 'asctime', 'created', 'exc_info', 'exc_text', 'filename', 'funcName',
'levelname', 'levelno', 'lineno', 'module', 'msecs', 'message', 'msg', 'name',
'pathname', 'process', 'processName', 'relativeCreated', 'stack_info', 'thread',
'threadName', 'taskName',
}
class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
payload: dict[str, object] = {
'timestamp': datetime.fromtimestamp(record.created, timezone.utc).isoformat(),
'severity': record.levelname,
'logger': record.name,
'message': record.getMessage(),
'event': getattr(record, 'event', 'log.message'),
}
span_context = trace.get_current_span().get_span_context()
if span_context.is_valid:
payload['trace_id'] = format(span_context.trace_id, '032x')
payload['span_id'] = format(span_context.span_id, '016x')
for key, value in record.__dict__.items():
if key in _STANDARD_FIELDS or key.startswith('_'):
continue
if isinstance(value, (str, int, float, bool)) or value is None:
payload[key] = value
if record.exc_info:
payload['exception.type'] = record.exc_info[0].__name__
return json.dumps(payload, ensure_ascii=False, separators=(',', ':'))
def safe_extra(event: str, **attributes: object) -> dict[str, object]:
blocked = {
'authorization', 'password', 'token', 'session_token', 'message_body',
'image_bytes', 's3_secret_access_key', 'signed_url',
}
extra: dict[str, object] = {'event': event}
for key, value in attributes.items():
normalized = key.lower()
if normalized in blocked or any(part in normalized for part in ('password', 'secret')):
continue
extra[key] = value
return extra