"""Structured JSON logging for Explorer Consultant Bot. Why JSON logs ------------- HF Spaces / Railway / any container orchestrator pipes stdout into a log aggregator. Plain text logs (`print(f"[ERROR] thing failed: {e}")`) are hard to parse, filter, or alert on at scale. JSON logs are machine-readable: each line is one event with `timestamp`, `level`, `logger`, `message`, and optional `exception` fields. Tools like Loki, CloudWatch, or Datadog ingest them with zero parsing config. Usage ----- from core.logging_config import get_logger logger = get_logger(__name__) logger.info("predictor loaded") logger.warning("model download retried", extra={"attempt": 2}) logger.error("prediction failed", exc_info=True) The first call to `setup_logging()` configures the root handler. Subsequent calls to `get_logger()` return child loggers that inherit the JSON formatter. """ from __future__ import annotations import json import logging import os import sys from datetime import datetime, timezone class JSONFormatter(logging.Formatter): """Render each log record as a single-line JSON object. Standard fields: timestamp (ISO 8601 UTC), level, logger, message, module. If the record carries `exc_info`, the formatted traceback is included. Any extra fields passed via `logger.X(..., extra={...})` are merged in. """ _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", } def format(self, record: logging.LogRecord) -> str: ts = datetime.fromtimestamp(record.created, tz=timezone.utc).isoformat() payload: dict = { "timestamp": ts, "level": record.levelname, "logger": record.name, "message": record.getMessage(), "module": record.module, } if record.exc_info: payload["exception"] = self.formatException(record.exc_info) # Merge any user-supplied extras (avoiding LogRecord internals) for key, value in record.__dict__.items(): if key not in self._RESERVED and not key.startswith("_"): try: json.dumps(value) # ensure JSON-safe payload[key] = value except (TypeError, ValueError): payload[key] = repr(value) return json.dumps(payload, ensure_ascii=False) _initialised = False def setup_logging(level: str | None = None) -> None: """Configure the root logger with JSON output. Idempotent.""" global _initialised if _initialised: return level_name = (level or os.environ.get("LOG_LEVEL", "INFO")).upper() log_level = getattr(logging, level_name, logging.INFO) root = logging.getLogger() # Clear any handlers uvicorn / FastAPI added before we ran for handler in root.handlers[:]: root.removeHandler(handler) handler = logging.StreamHandler(sys.stdout) handler.setFormatter(JSONFormatter()) root.addHandler(handler) root.setLevel(log_level) # Quiet down noisy third-party loggers logging.getLogger("uvicorn.access").setLevel(logging.WARNING) logging.getLogger("huggingface_hub").setLevel(logging.WARNING) _initialised = True def get_logger(name: str) -> logging.Logger: """Return a logger that inherits the JSON config. Call setup_logging first.""" if not _initialised: setup_logging() return logging.getLogger(name)