k9cli's picture
Flatten package contents to repo root
de01f6a verified
Raw History Blame Contribute Delete
1.07 kB
"""Centralised logging configuration."""
from __future__ import annotations
import logging
import sys
from typing import Optional
_CONFIGURED = False
_DEFAULT_FORMAT = "%(asctime)s | %(levelname)-7s | %(name)s | %(message)s"
def setup_logging(level: str | int = "INFO", *, fmt: Optional[str] = None) -> None:
"""Configure the root logger once for the whole application."""
global _CONFIGURED
if isinstance(level, str):
level = logging.getLevelName(level.upper())
handler = logging.StreamHandler(stream=sys.stderr)
handler.setFormatter(logging.Formatter(fmt or _DEFAULT_FORMAT))
root = logging.getLogger()
root.setLevel(level)
# Avoid duplicate handlers on repeated calls (e.g. in tests).
for existing in list(root.handlers):
root.removeHandler(existing)
root.addHandler(handler)
_CONFIGURED = True
def get_logger(name: str) -> logging.Logger:
"""Return a module logger, ensuring logging has been configured."""
if not _CONFIGURED:
setup_logging()
return logging.getLogger(name)