Spaces:
Runtime error

ai-tester-platform / src /utils /logging.py
BattleFiven's picture
deploy: round 6 save_intermediate light (sha 05316bb)
ed86a97
Raw History Blame Contribute Delete
4.2 kB
"""Centralised logging configuration.
Single source of truth for logger setup across API, core and CLI.
Importing this module is a no-op for the second caller — ``configure_logging``
is idempotent and only configures the root logger once.
Usage::
from src.utils.logging import get_logger, configure_logging
configure_logging() # call once on app startup (lifespan, CLI entry)
logger = get_logger(__name__)
logger.info("startup ok", extra={"version": app_version})
Format:
- Default: human-readable text with timestamp, level, name, message.
- When ``LOG_FORMAT=json`` (or stdlib JSON requested), emits a single
JSON object per line. Useful in production / Render where logs are
ingested by an aggregator.
Levels:
Controlled by ``LOG_LEVEL`` env var (DEBUG/INFO/WARNING/ERROR).
Defaults to INFO. In tests, set ``LOG_LEVEL=ERROR`` to silence noise.
"""
from __future__ import annotations
import json
import logging
import logging.config
import os
import sys
from typing import Any, Dict, Optional
from src.utils.env import env_str
_CONFIGURED = False
class _JsonFormatter(logging.Formatter):
"""Minimal JSON formatter — no external dependency.
Emits one JSON line per record with the canonical fields. Extra fields
attached via ``logger.info(..., extra={...})`` are merged into the root
object. Exception info is rendered as a multi-line ``exc_info`` string.
"""
_RESERVED = {
"name",
"msg",
"args",
"levelname",
"levelno",
"pathname",
"filename",
"module",
"exc_info",
"exc_text",
"stack_info",
"lineno",
"funcName",
"created",
"msecs",
"relativeCreated",
"thread",
"threadName",
"processName",
"process",
"message",
"asctime",
"taskName",
}
def format(self, record: logging.LogRecord) -> str: # noqa: D401
payload: Dict[str, Any] = {
"ts": self.formatTime(record, "%Y-%m-%dT%H:%M:%S"),
"level": record.levelname,
"logger": record.name,
"msg": record.getMessage(),
}
for key, value in record.__dict__.items():
if key in self._RESERVED or key.startswith("_"):
continue
try:
json.dumps(value)
payload[key] = value
except (TypeError, ValueError):
payload[key] = repr(value)
if record.exc_info:
payload["exc_info"] = self.formatException(record.exc_info)
return json.dumps(payload, ensure_ascii=False)
def configure_logging(level: Optional[str] = None, fmt: Optional[str] = None) -> None:
"""Configure the root logger. Idempotent — safe to call multiple times."""
global _CONFIGURED
if _CONFIGURED:
return
level_name = (level or env_str("LOG_LEVEL", "INFO")).upper()
log_level = getattr(logging, level_name, logging.INFO)
fmt_choice = (fmt or env_str("LOG_FORMAT", "text")).strip().lower()
handler = logging.StreamHandler(stream=sys.stdout)
if fmt_choice == "json":
handler.setFormatter(_JsonFormatter())
else:
handler.setFormatter(
logging.Formatter(
fmt="%(asctime)s %(levelname)-7s %(name)s: %(message)s",
datefmt="%Y-%m-%dT%H:%M:%S",
)
)
handler.setLevel(log_level)
root = logging.getLogger()
# Replace any pre-existing handlers (uvicorn installs its own — keep ours
# last so duplicate output is avoided).
for existing in list(root.handlers):
root.removeHandler(existing)
root.addHandler(handler)
root.setLevel(log_level)
# Quiet down noisy third-party libraries by default.
for noisy in ("httpx", "urllib3", "asyncio", "websockets"):
logging.getLogger(noisy).setLevel(max(log_level, logging.WARNING))
_CONFIGURED = True
def get_logger(name: str) -> logging.Logger:
"""Return a configured logger. Auto-configures on first call."""
if not _CONFIGURED:
configure_logging()
return logging.getLogger(name)