将 4 个根目录核心模块迁移到合理位置: - path_config.py -> douyin/core/path_config.py - version.py -> douyin/core/version.py - Underlying_Operations.py -> douyin/core/underlying_operations.py - unified_logger.py -> douyin/logging/unified_logger.py 配套更新所有 import: - path_config: 41 处 import 改为 douyin.core.path_config - version: 4 处改为 douyin.core.version - unified_logger: 5 处改为 douyin.logging.unified_logger - Underlying_Operations: 14 处改为 douyin.core.underlying_operations 修复 path_config.PROJECT_ROOT 计算(向上 2 级而非当前目录)。 验证:python -m compileall 全项目通过。 Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
63 lines
2.6 KiB
Python
63 lines
2.6 KiB
Python
"""错误日志记录模块:记录详细错误、上下文与推荐恢复建议"""
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import traceback
|
|
import os
|
|
from typing import Any, Dict, Optional
|
|
from douyin.core import path_config
|
|
|
|
logger = None
|
|
|
|
def _init_logger():
|
|
global logger
|
|
if logger is not None:
|
|
return
|
|
log_path = path_config.get_error_log_path() if hasattr(path_config, "get_error_log_path") else os.path.join(path_config.get_logs_dir(), "error.log")
|
|
os.makedirs(os.path.dirname(log_path), exist_ok=True)
|
|
import logging.handlers
|
|
logger = logging.getLogger("error_logger")
|
|
if not logger.handlers:
|
|
handler = logging.handlers.RotatingFileHandler(log_path, maxBytes=5*1024*1024, backupCount=5, encoding="utf-8")
|
|
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
|
|
handler.setFormatter(formatter)
|
|
logger.addHandler(handler)
|
|
logger.setLevel(logging.INFO)
|
|
|
|
class ErrorLogger:
|
|
def __init__(self) -> None:
|
|
_init_logger()
|
|
def log_exception(self, exc: BaseException, context: Optional[Dict[str, Any]] = None, level: str = "ERROR") -> None:
|
|
if not logger:
|
|
_init_logger()
|
|
if logger is None:
|
|
# 如果仍然无法初始化 logger,则退回到标准输出,避免抛出异常
|
|
print(f"[ErrorLogger] {type(exc).__name__}: {exc}")
|
|
return
|
|
tb = traceback.format_exc()
|
|
ctx = ", ".join(f"{k}={v}" for k, v in (context or {}).items()) if context else ""
|
|
msg = f"Exception: {type(exc).__name__}: {exc}"
|
|
if ctx:
|
|
msg += f" | context: {ctx}"
|
|
if tb:
|
|
msg += f"\nTraceback:\n{tb}"
|
|
logger.log(getattr(logging, level, logging.ERROR), msg)
|
|
def log_error(self, msg: str, context: Optional[Dict[str, Any]] = None, level: str = "ERROR") -> None:
|
|
if not logger:
|
|
_init_logger()
|
|
if logger is None:
|
|
print(f"[ErrorLogger] {msg}")
|
|
return
|
|
full = msg
|
|
if context:
|
|
full += " | " + ", ".join(f"{k}={v}" for k, v in context.items())
|
|
logger.log(getattr(logging, level, logging.ERROR), full)
|
|
def log_warning(self, msg: str, context: Optional[Dict[str, Any]] = None) -> None:
|
|
self.log_error(msg, context=context, level="WARNING")
|
|
def capture_error_context(self, **ctx) -> Dict[str, Any]:
|
|
return dict(ctx)
|
|
def log_error_with_context(self, exc: BaseException, context: Optional[Dict[str, Any]] = None, level: str = "ERROR") -> None:
|
|
self.log_exception(exc, context=context, level=level)
|
|
|
|
__all__ = ["ErrorLogger"]
|