File size: 3,683 Bytes
fa67054
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
"""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)