- Introduced new logging modules for action tracking, error logging, and performance tracking to improve observability. - Added functions for retrieving debug and error log paths in `path_config.py`. - Updated various components to utilize the new logging system, enhancing error handling and performance diagnostics. - Implemented a GUI component for viewing error logs, improving user experience in monitoring application issues. - Cleaned up unnecessary blank lines and improved code readability across multiple files.
58 lines
2.3 KiB
Python
58 lines
2.3 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()
|
|
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()
|
|
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"]
|
|
|
|
|