Spaces:
Runtime error

File size: 4,196 Bytes
ed86a97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
"""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)