Files
stack/src/bcda/log.py
2026-02-09 23:39:08 -05:00

154 lines
4.4 KiB
Python

"""JSONL structured logging for the bcda namespace.
Provides a standard-library ``logging.Handler`` that writes each log
record as a single JSON line. Captures the full detail of every
operation — timestamps, levels, logger names, messages, and any
structured ``extra`` fields passed by callers.
Usage::
from bcda.log import setup
# Attach JSONL handler to the 'bcda' logger hierarchy.
setup("data/bcda/log.jsonl")
# All bcda.client / bcda.store logs now land in that file:
# {"ts": "2026-02-09T14:30:00.123456", "level": "INFO", ...}
"""
from __future__ import annotations
import json
import logging
from datetime import datetime, timezone
from pathlib import Path
# Keys that belong to the stdlib LogRecord internals and should
# not leak into the structured JSONL output.
_BUILTIN_ATTRS = frozenset(
{
"args",
"created",
"exc_info",
"exc_text",
"filename",
"funcName",
"levelname",
"levelno",
"lineno",
"module",
"msecs",
"message",
"msg",
"name",
"pathname",
"process",
"processName",
"relativeCreated",
"stack_info",
"taskName",
"thread",
"threadName",
}
)
class JsonlHandler(logging.Handler):
"""Write log records as JSON lines to an append-only file.
Each line is a self-contained JSON object with at least::
{"ts": "...", "level": "INFO", "logger": "bcda.client",
"message": "Downloading Patient -> ..."}
Any ``extra`` dict keys passed via the logging call are merged
into the object, giving callers a clean way to attach structured
context (``job_key``, ``resource_type``, ``bytes``, etc.).
Parameters
----------
path : str or Path
Destination JSONL file. Created (with parents) if missing.
Opened in append mode so the file grows indefinitely.
"""
def __init__(self, path: str | Path) -> None:
super().__init__()
self._path = Path(path)
self._path.parent.mkdir(parents=True, exist_ok=True)
self._file = open(self._path, "a", encoding="utf-8") # noqa: SIM115
def emit(self, record: logging.LogRecord) -> None:
try:
entry: dict = {
"ts": datetime.fromtimestamp(
record.created,
tz=timezone.utc,
).isoformat(),
"level": record.levelname,
"logger": record.name,
"message": record.getMessage(),
}
# Merge caller-supplied extras (skip stdlib internals).
for key, value in record.__dict__.items():
if key in _BUILTIN_ATTRS or key.startswith("_"):
continue
if key in entry:
continue
try:
json.dumps(value)
entry[key] = value
except (TypeError, ValueError):
entry[key] = repr(value)
if record.exc_info and record.exc_info[1] is not None:
entry["exception"] = self.format(record).split("\n")
self._file.write(json.dumps(entry, default=str) + "\n")
self._file.flush()
except Exception:
self.handleError(record)
def close(self) -> None:
try:
self._file.flush()
self._file.close()
except Exception:
pass
super().close()
def setup(
path: str | Path = "data/bcda/log.jsonl",
*,
level: int = logging.DEBUG,
) -> logging.Logger:
"""Attach a :class:`JsonlHandler` to the ``bcda`` logger.
Returns the ``bcda`` root logger so callers can further
configure it if needed. Safe to call multiple times — a
second call with the same path is a no-op.
Parameters
----------
path : str or Path
JSONL destination file.
level : int
Minimum level to capture. Defaults to ``DEBUG``.
"""
logger = logging.getLogger("bcda")
# Avoid duplicate handlers for the same file.
resolved = str(Path(path).resolve())
for h in logger.handlers:
if isinstance(h, JsonlHandler) and str(h._path.resolve()) == resolved:
return logger
handler = JsonlHandler(path)
handler.setLevel(level)
logger.addHandler(handler)
if logger.level == logging.NOTSET or logger.level > level:
logger.setLevel(level)
return logger