45 lines
1.3 KiB
Python
45 lines
1.3 KiB
Python
"""structlog 配置:开发彩色、生产 JSON。"""
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import sys
|
|
|
|
import structlog
|
|
|
|
from app.core.config import settings
|
|
|
|
|
|
def configure_logging() -> None:
|
|
shared_processors: list = [
|
|
structlog.contextvars.merge_contextvars,
|
|
structlog.processors.add_log_level,
|
|
structlog.processors.TimeStamper(fmt="iso", utc=True),
|
|
structlog.processors.StackInfoRenderer(),
|
|
]
|
|
|
|
if settings.is_dev:
|
|
renderer = structlog.dev.ConsoleRenderer(colors=True)
|
|
else:
|
|
renderer = structlog.processors.JSONRenderer()
|
|
|
|
structlog.configure(
|
|
processors=[*shared_processors, renderer],
|
|
wrapper_class=structlog.make_filtering_bound_logger(logging.INFO),
|
|
context_class=dict,
|
|
logger_factory=structlog.PrintLoggerFactory(file=sys.stdout),
|
|
cache_logger_on_first_use=True,
|
|
)
|
|
|
|
# 让 uvicorn / fastapi 的标准 logging 也走 structlog
|
|
logging.basicConfig(
|
|
format="%(message)s",
|
|
stream=sys.stdout,
|
|
level=logging.INFO,
|
|
)
|
|
for name in ("uvicorn", "uvicorn.error", "uvicorn.access", "sqlalchemy.engine"):
|
|
logging.getLogger(name).handlers.clear()
|
|
logging.getLogger(name).propagate = True
|
|
|
|
|
|
logger = structlog.get_logger()
|