|
| 1 | +"""Structured JSON log formatter for production deployments.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import json |
| 6 | +import logging |
| 7 | +import time |
| 8 | +from typing import Any |
| 9 | + |
| 10 | + |
| 11 | +class JsonFormatter(logging.Formatter): |
| 12 | + """Emit log records as single-line JSON objects. |
| 13 | +
|
| 14 | + Output format (one JSON object per line): |
| 15 | + {"ts":"2025-05-21T06:00:01Z","level":"INFO","logger":"oikb.daemon","msg":"Synced ..."} |
| 16 | +
|
| 17 | + Compatible with Datadog, Splunk, ELK, CloudWatch, Loki, and any |
| 18 | + JSON-aware log aggregator. |
| 19 | + """ |
| 20 | + |
| 21 | + def format(self, record: logging.LogRecord) -> str: |
| 22 | + entry: dict[str, Any] = { |
| 23 | + "ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(record.created)), |
| 24 | + "level": record.levelname, |
| 25 | + "logger": record.name, |
| 26 | + "msg": record.getMessage(), |
| 27 | + } |
| 28 | + |
| 29 | + if record.exc_info and record.exc_info[1] is not None: |
| 30 | + entry["exception"] = self.formatException(record.exc_info) |
| 31 | + |
| 32 | + # Merge any extra fields passed via `log.info("msg", extra={...})`. |
| 33 | + for key in ("source", "kb_id", "status", "duration_ms", |
| 34 | + "files_added", "files_modified", "files_deleted"): |
| 35 | + val = getattr(record, key, None) |
| 36 | + if val is not None: |
| 37 | + entry[key] = val |
| 38 | + |
| 39 | + return json.dumps(entry, default=str, ensure_ascii=False) |
| 40 | + |
| 41 | + |
| 42 | +def configure_logging(log_format: str = "text", log_level: str = "INFO") -> None: |
| 43 | + """Configure root logging for the daemon. |
| 44 | +
|
| 45 | + Args: |
| 46 | + log_format: "text" for human-readable, "json" for structured JSON lines. |
| 47 | + log_level: Standard Python log level name. |
| 48 | + """ |
| 49 | + root = logging.getLogger() |
| 50 | + root.setLevel(getattr(logging, log_level.upper(), logging.INFO)) |
| 51 | + |
| 52 | + # Remove any existing handlers (uvicorn may add its own). |
| 53 | + root.handlers.clear() |
| 54 | + |
| 55 | + handler = logging.StreamHandler() |
| 56 | + |
| 57 | + if log_format == "json": |
| 58 | + handler.setFormatter(JsonFormatter()) |
| 59 | + else: |
| 60 | + handler.setFormatter( |
| 61 | + logging.Formatter("%(asctime)s %(levelname)-8s %(name)s %(message)s") |
| 62 | + ) |
| 63 | + |
| 64 | + root.addHandler(handler) |
0 commit comments