示例工程 38-observability-otel

38-observability-otel/02-dictconfig-full/dictconfig_full.py

python · 1.5 KB

"""用 dictConfig 同时配置控制台与文件 handler。"""
 
from __future__ import annotations
 
import logging
import logging.config
import tempfile
from pathlib import Path
 
 
def configure(path: Path) -> None:
    config = {
        "version": 1,
        "disable_existing_loggers": False,
        "formatters": {
            "plain": {"format": "%(levelname)s %(name)s %(message)s"},
        },
        "handlers": {
            "console": {
                "class": "logging.StreamHandler",
                "stream": "ext://sys.stdout",
                "formatter": "plain",
            },
            "file": {
                "class": "logging.FileHandler",
                "filename": str(path),
                "mode": "w",
                "encoding": "utf-8",
                "formatter": "plain",
            },
        },
        "loggers": {
            "obs.dict": {
                "level": "DEBUG",
                "handlers": ["console", "file"],
                "propagate": False,
            },
        },
    }
    logging.config.dictConfig(config)
 
 
def run(path: Path) -> list[str]:
    configure(path)
    logger = logging.getLogger("obs.dict")
    logger.info("hello")
    logger.warning("warn")
    for handler in logger.handlers:
        handler.flush()
    return path.read_text(encoding="utf-8").strip().splitlines()
 
 
def main() -> None:
    with tempfile.TemporaryDirectory() as tmp:
        lines = run(Path(tmp) / "app.log")
    print(f"file_lines: {lines}")
 
 
if __name__ == "__main__":
    main()