Files
douyin_guaji-main/douyin/logging/error_logger.py
T
Your Name 223c127e11 chore: Clean up and refactor codebase for improved maintainability
- Removed obsolete command-line test parameters from `run_cli.py` to streamline functionality.
- Introduced a new `ocr_preprocess.py` module for unified OCR image preprocessing, enhancing recognition stability.
- Updated various components to utilize the new preprocessing function, improving code organization and readability.
- Adjusted configuration values in `config.json` for better performance and consistency.
- Added comprehensive technical documentation for the Douyin project, detailing code modification standards and operational guidelines.
- Cleaned up excessive blank lines across multiple files to enhance overall readability.
2025-12-30 23:11:34 +08:00

84 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"]