123456789101112131415161718192021222324252627282930313233343536373839404142 |
- import logging.config
- import yaml
- import os
- from pathlib import Path
- import pathlib
- def setup_logging():
- """动态定位配置文件路径"""
- try:
- # 获取当前脚本所在目录(logger.py位置)
- script_dir = pathlib.Path(__file__).parent.resolve()
- # 构建配置文件的正确相对路径
- config_path = script_dir / "logging_config.yaml"
- print(f"配置文件路径: {config_path}")
- if not config_path.exists():
- raise FileNotFoundError(f"日志配置文件不存在: {config_path}")
- with open(config_path, 'rt', encoding='utf-8') as f:
- config = yaml.safe_load(f)
- logging.config.dictConfig(config)
- except Exception as e:
- logging.basicConfig(level=logging.INFO)
- logging.error("日志配置失败,使用基础配置: %s", e)
- print(f"⚠️ 关键错误: {str(e)}")
- def get_logger(name=None):
- """获取日志记录器"""
- return logging.getLogger(name or 'root')
- class ExceptionLogger:
- """异常记录工具"""
- @staticmethod
- def log_exception(logger, message):
- """记录异常及堆栈跟踪"""
- logger.exception(message, exc_info=True)
|