Files
douyin_guaji-main/douyin/logging/error_logger.py
T
Your Name 0b5f150691 Refactor and clean up code across multiple scripts
- Removed trailing whitespace and ensured files end with a single newline in cleanup_unused_files.py.
- Added fix_trailing_whitespace.py to batch remove trailing whitespace from Python files.
- Updated install_dependencies.py to improve dependency installation prompts.
- Cleaned up pick_coords.py by removing unnecessary whitespace and improving code readability.
- Enhanced region_selector.py by disabling specific pylint checks for better compatibility with third-party libraries.
- Improved WPS流程图生成工具.py by cleaning up whitespace and enhancing readability.
- Updated __init__.py in typings to remove unnecessary lines.
- Modified app.js to adjust default configuration values and clean up unused code.
2026-01-02 23:57:03 +08:00

63 lines
2.6 KiB
Python

"""错误日志记录模块:记录详细错误、上下文与推荐恢复建议"""
from __future__ import annotations
import logging
import traceback
import os
from typing import Any, Dict, Optional
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"]