43 lines
1.6 KiB
Python
43 lines
1.6 KiB
Python
import json
|
|
import logging
|
|
from datetime import UTC, datetime
|
|
from typing import Final, override
|
|
|
|
# uvicorn configures these loggers with its own text handlers before it imports
|
|
# the application. They are routed through the service handler instead, so
|
|
# that no uvicorn record prints exception text or a traceback.
|
|
UVICORN_LOGGERS: Final = ("uvicorn", "uvicorn.error", "uvicorn.access")
|
|
|
|
|
|
class JsonFormatter(logging.Formatter):
|
|
"""Format records as JSON lines without exception text or tracebacks.
|
|
|
|
Exception messages may contain resume text, contact data, or model output,
|
|
so a record with exception information keeps only the exception type.
|
|
"""
|
|
|
|
@override
|
|
def format(self, record: logging.LogRecord) -> str:
|
|
entry: dict[str, str] = {
|
|
"timestamp": datetime.now(UTC).isoformat(),
|
|
"level": record.levelname.lower(),
|
|
"logger": record.name,
|
|
"message": record.getMessage(),
|
|
}
|
|
if record.exc_info and record.exc_info[0] is not None:
|
|
entry["exception_type"] = record.exc_info[0].__name__
|
|
return json.dumps(entry, ensure_ascii=False, separators=(",", ":"))
|
|
|
|
|
|
def configure_logging() -> None:
|
|
handler = logging.StreamHandler()
|
|
handler.setFormatter(JsonFormatter())
|
|
root_logger = logging.getLogger()
|
|
root_logger.handlers.clear()
|
|
root_logger.addHandler(handler)
|
|
root_logger.setLevel(logging.INFO)
|
|
for name in UVICORN_LOGGERS:
|
|
uvicorn_logger = logging.getLogger(name)
|
|
uvicorn_logger.handlers.clear()
|
|
uvicorn_logger.propagate = True
|