首页 > 解决方案 > 在 django 中间件中检索堆栈跟踪

问题描述

当 django 中间件的服务器端出现故障时,如何获取堆栈跟踪?这是我尝试过的,它只给我信息,而不是完整的堆栈。

class MonitorMiddleware(object):
    def process_exception(self, request, exception):
        self.error = exception.message

标签: django

解决方案


从评论中回答“检索错误堆栈跟踪以保存到数据库”:

https://docs.python.org/3/library/traceback.html

使用 的方法traceback将异常跟踪转换为字符串,然后您可以将其存储在数据库中。

同样在上面的页面上:

3.5 版中的新功能。

StackSummary 对象表示准备好格式化的调用堆栈。

带有异常对象的简短示例:

>>> an_error = IndexError('tuple index out of range')
>>> traceback.print_exception(type(an_error), an_error, an_error.__traceback__)
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
IndexError: list index out of range

另请参阅从异常对象中提取回溯信息:您不需要重新引发异常,但是回溯在__traceback__属性中。


推荐阅读