Source code for s365b.core.logging
"""Structured logging setup.
All processes log through :mod:`structlog`. In containers the output is one
JSON object per line on stdout, which ``docker logs`` and log shippers read
directly.
"""
from __future__ import annotations
import logging
import sys
import structlog
from structlog._config import BoundLoggerLazyProxy
[docs]
def configure_logging(level: str = "INFO", fmt: str = "json") -> None:
"""Configure structlog and the standard library logger.
Args:
level: Minimum level name, e.g. ``"INFO"``.
fmt: ``"json"`` for machine-readable output, ``"console"`` for
human-friendly output during development.
"""
renderer: structlog.typing.Processor = (
structlog.processors.JSONRenderer() if fmt == "json" else structlog.dev.ConsoleRenderer()
)
shared: list[structlog.typing.Processor] = [
structlog.contextvars.merge_contextvars,
structlog.processors.add_log_level,
structlog.processors.TimeStamper(fmt="iso", utc=True),
structlog.processors.StackInfoRenderer(),
structlog.processors.format_exc_info,
]
# Imported here: the run log needs the database models, which log.
from s365b.core.runlog import capture
shared.append(capture)
structlog.configure(
processors=[*shared, renderer],
wrapper_class=structlog.make_filtering_bound_logger(logging.getLevelName(level)),
logger_factory=structlog.PrintLoggerFactory(sys.stdout),
cache_logger_on_first_use=True,
)
# Route third-party stdlib logging (uvicorn, procrastinate, httpx) the same way.
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(
structlog.stdlib.ProcessorFormatter(
foreign_pre_chain=[structlog.stdlib.add_logger_name, *shared],
processors=[structlog.stdlib.ProcessorFormatter.remove_processors_meta, renderer],
)
)
root = logging.getLogger()
root.handlers[:] = [handler]
root.setLevel(level)
# httpx logs every request URL at INFO; some URLs carry credentials
# (a mailbox import session's). The Graph client logs requests itself.
for noisy in ("httpx", "httpcore"):
logging.getLogger(noisy).setLevel(max(logging.WARNING, root.level))
[docs]
def get_logger(name: str | None = None) -> structlog.typing.FilteringBoundLogger:
"""Return a structlog logger.
Args:
name: Optional logger name, bound as the ``logger`` field.
Returns:
A bound structlog logger.
"""
# Lazy: the logger takes the configuration in force when it first logs,
# not when its module was imported.
# (structlog.get_logger takes no "logger" field: its own parameter.)
log: structlog.typing.FilteringBoundLogger = BoundLoggerLazyProxy( # type: ignore[assignment]
None, initial_values={"logger": name} if name else {}, logger_factory_args=()
)
return log