28 lines
770 B
Python
28 lines
770 B
Python
|
|
"""Structured JSON logging (NF-observability)."""
|
||
|
|
|
||
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import logging
|
||
|
|
import sys
|
||
|
|
|
||
|
|
from pythonjsonlogger.jsonlogger import JsonFormatter
|
||
|
|
|
||
|
|
|
||
|
|
def configure_logging(level: str = "INFO", *, as_json: bool = True) -> None:
|
||
|
|
"""Configure the root logger once at app start."""
|
||
|
|
handler = logging.StreamHandler(sys.stdout)
|
||
|
|
if as_json:
|
||
|
|
formatter: logging.Formatter = JsonFormatter(
|
||
|
|
"%(asctime)s %(levelname)s %(name)s %(message)s"
|
||
|
|
)
|
||
|
|
else:
|
||
|
|
formatter = logging.Formatter(
|
||
|
|
"%(asctime)s %(levelname)-8s %(name)s: %(message)s"
|
||
|
|
)
|
||
|
|
handler.setFormatter(formatter)
|
||
|
|
|
||
|
|
root = logging.getLogger()
|
||
|
|
root.handlers.clear()
|
||
|
|
root.addHandler(handler)
|
||
|
|
root.setLevel(level.upper())
|