Python脚本异常捕获怎样记录堆栈

wen 实用脚本 11

本文目录导读:

Python脚本异常捕获怎样记录堆栈

  1. 使用 traceback 模块(推荐)
  2. 使用 logging 模块的 exc_info 参数
  3. 使用 sys.exc_info()
  4. 自定义异常处理函数
  5. 使用装饰器自动记录
  6. 完整的生产级示例

在Python中记录异常堆栈信息有几种常用方法:

使用 traceback 模块(推荐)

完整堆栈记录

import traceback
import logging
try:
    # 你的代码
    result = 1 / 0
except Exception:
    # 记录完整堆栈
    error_msg = traceback.format_exc()
    logging.error(f"发生异常:\n{error_msg}")

仅记录当前异常堆栈

import traceback
try:
    result = 1 / 0
except Exception as e:
    # 获取当前异常的堆栈信息
    stack = traceback.format_exc()
    print(f"错误: {e}\n堆栈:\n{stack}")

使用 logging 模块的 exc_info 参数

import logging
logging.basicConfig(
    level=logging.ERROR,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
try:
    result = 1 / 0
except Exception:
    # exc_info=True 会自动记录异常堆栈
    logging.error("发生错误", exc_info=True)

使用 sys.exc_info()

import sys
import traceback
try:
    result = 1 / 0
except:
    exc_type, exc_value, exc_traceback = sys.exc_info()
    # 获取堆栈信息
    stack_trace = traceback.extract_tb(exc_traceback)
    # 记录到文件
    with open('error.log', 'a') as f:
        f.write(f"异常类型: {exc_type}\n")
        f.write(f"异常值: {exc_value}\n")
        f.write("堆栈信息:\n")
        traceback.print_tb(exc_traceback, file=f)
        f.write("\n---\n")

自定义异常处理函数

import traceback
import logging
from datetime import datetime
def log_exception(exc, additional_info=""):
    """记录异常和堆栈信息"""
    error_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    error_msg = traceback.format_exc()
    log_content = f"""
时间: {error_time}
附加信息: {additional_info}
异常: {exc}
堆栈:
{error_msg}
{'='*50}
"""
    # 写入日志文件
    with open('error.log', 'a', encoding='utf-8') as f:
        f.write(log_content)
    # 也打印到控制台
    print(log_content)
# 使用示例
try:
    x = [1, 2, 3]
    value = x[5]
except Exception as e:
    log_exception(e, "数组索引越界")

使用装饰器自动记录

import traceback
import functools
def log_exception(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            # 记录异常到文件
            with open('error.log', 'a') as f:
                f.write(f"函数: {func.__name__}\n")
                f.write(f"参数: args={args}, kwargs={kwargs}\n")
                f.write(f"异常: {e}\n")
                f.write(f"堆栈:\n{traceback.format_exc()}\n")
                f.write("-" * 50 + "\n")
            raise
    return wrapper
# 使用装饰器
@log_exception
def risky_operation(x, y):
    return x / y
# 测试
risky_operation(1, 0)

完整的生产级示例

import traceback
import logging
import sys
from datetime import datetime
class ExceptionLogger:
    def __init__(self, log_file='error.log'):
        self.log_file = log_file
        # 配置logging
        logging.basicConfig(
            level=logging.ERROR,
            format='%(asctime)s - %(levelname)s - %(message)s',
            handlers=[
                logging.FileHandler(log_file, encoding='utf-8'),
                logging.StreamHandler(sys.stderr)
            ]
        )
        self.logger = logging.getLogger(__name__)
    def log_exception(self, context=""):
        """记录异常堆栈,包含上下文信息"""
        error_msg = traceback.format_exc()
        self.logger.error(f"上下文: {context}\n{error_msg}")
    def handle_exception(self, context=""):
        """作为上下文管理器使用"""
        try:
            yield
        except Exception as e:
            self.log_exception(f"{context} - {e}")
# 使用示例
logger = ExceptionLogger()
# 方法1: 直接使用
try:
    result = 1 / 0
except Exception:
    logger.log_exception("除法运算")
# 方法2: 作为上下文管理器
with logger.handle_exception("数据处理"):
    data = [1, 2, 3]
    print(data[10])
  1. traceback.format_exc() - 获取完整堆栈字符串(最常用)
  2. logging.exc_info=True - 自动记录堆栈
  3. sys.exc_info() - 获取异常详细信息
  4. 记录到文件 - 便于后续分析
  5. 包含上下文信息 - 更容易定位问题

选择哪种方法取决于你的具体需求,对于大多数情况,使用 traceback.format_exc() 配合 logging 模块就足够了。

抱歉,评论功能暂时关闭!