PMFlow/backend/app/core/logging.py

60 lines
1.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
结构化日志配置
使用 structlog 实现结构化、可观测的日志,便于生产环境排查与聚合。
"""
import logging
import sys
from typing import Any
# 尝试使用 structlog,若未安装则回退到标准 logging
try:
import structlog
USE_STRUCTLOG = True
except ImportError:
USE_STRUCTLOG = False
def configure_logging(debug: bool = False) -> None:
"""
配置应用日志
Args:
debug: 是否为调试模式
"""
log_level = logging.DEBUG if debug else logging.INFO
if USE_STRUCTLOG:
structlog.configure(
processors=[
structlog.stdlib.filter_by_level,
structlog.stdlib.add_logger_name,
structlog.stdlib.add_log_level,
structlog.stdlib.PositionalArgumentsFormatter(),
structlog.processors.TimeStamper(fmt="iso"),
structlog.processors.StackInfoRenderer(),
structlog.processors.format_exc_info,
structlog.processors.UnicodeDecoder(),
structlog.dev.ConsoleRenderer() if debug else structlog.processors.JSONRenderer(),
],
wrapper_class=structlog.stdlib.BoundLogger,
context_class=dict,
logger_factory=structlog.stdlib.LoggerFactory(),
cache_logger_on_first_use=True,
)
else:
logging.basicConfig(
level=log_level,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
stream=sys.stdout,
)
def get_logger(name: str):
"""获取 logger 实例"""
if USE_STRUCTLOG:
return structlog.get_logger(name)
return logging.getLogger(name)