python - 拦截用于记录的 Django 500 错误,而不创建/提供自定义 500.html

标签 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 事件?

最佳答案

不是制作自定义 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',
]

关于python - 拦截用于记录的 Django 500 错误,而不创建/提供自定义 500.html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67908161/

相关文章:

python - SQL Server - 查询日志?

python - while循环在django中递增范围

angularjs - 对 API 的跨源 Ajax 请求返回 500(内部服务器错误)响应

python - 使用 Python 解析 JSON

python - 准备一个复杂的 python 项目以提交到启动板

python - Pandas 数据框 - RemoteDataError - Python

laravel - Laravel 6 API不会在日志中写入错误500

python - 连接数据帧,重视特定数据帧中的重复行

django - 包含Django templatetag用户对象

asp.net-mvc-4 - 为什么超过指定 maxRequestLength 的请求会以(看似)不相关的错误响应?