拦截 Django 500 错误以进行日志记录,而不创建/提供自定义 500.html

时间:2021-06-09 16:27:32

标签: python django http-status-code-500

为了记录触发服务器错误 500 的“某些依赖项,某处很深”的错误,而不是由于 DEBUG=False 在控制台登录生产实例中的堆栈跟踪,我实现了标准的自定义 500 处理程序,这是一个公平的关于打印 500 错误的堆栈跟踪的 Stackoverflow 问题数量推荐:

import sys
import traceback

def server_error_500_handler(request):
    type, value, tb = sys.exc_info()
    print('\n----intercepted 500 error stack trace----')
    print(value)
    print(type)
    print(traceback.format_exception(type, value, tb))
    print('----\n')

然而,这些也都说以 render(request, '500.html') 结尾,而我不想提供自定义的 500 页,但希望代码“返回”(如果有这样的事情)只是服务于 Django 本身已经做的任何事情。有没有办法让它做到这一点?或者,有没有办法在不劫持 500 错误返回码路径的情况下监听 500 事件?

1 个答案:

答案 0 :(得分:3)

不要制作自定义 500 处理程序,而是制作您自己的 custom middleware 并在其中实现 process_exception 方法:

import traceback


class Log500ErrorsMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        return response
    
    def process_exception(self, request, exception):
        print('\n----intercepted 500 error stack trace----')
        print(exception)
        print(type(exception))
        tb = exception.__traceback__
        print(traceback.format_exception(type(exception), exception, tb))
        print('----\n')
        return None # Let other middlewares do further processing

然后将它添加到 MIDDLEWARE 设置中,一直到最后,因为中间件在响应/异常阶段以自下而上的顺序运行,所以如果你把它放在最后,它总是会运行(某些中间件可以决定短路并以其他方式返回响应,因此在它之后进行任何操作都可能会阻止它运行)。

MIDDLEWARE = [
    ...
    'path.to.Log500ErrorsMiddleware',
]
相关问题