我们使用中间件来处理生产中发生的任何异常。基本思想是将调试 html 保存到文件系统上的某个位置,该位置可以通过受密码保护的视图提供服务,然后将生成的视图的链接发送给需要它的人。
这是一个基本的实现:
from django.conf import settings
from django.core.mail import send_mail
from django.views import debug
import traceback
import hashlib
import sys
class ExceptionMiddleware(object):
def process_exception(self, request, exception):
if isinstance(exception, Http404):
return
traceback = traceback.format_exc()
traceback_hash = hashlib.md5(traceback).hexdigest()
traceback_name = '%s.html' % traceback_hash
traceback_path = os.path.join(settings.EXCEPTIONS_DIR, traceback_name)
reporter = debug.ExceptionReporter(request, *sys.exc_info())
with open(traceback_path, 'w') as f:
f.write(reporter.get_traceback_html().encode("utf-8"))
send_mail(
'Error at %s' % request.path,
request.build_absolute_uri(reverse('exception', args=(traceback_name, ))),
FROM_EMAIL,
TO_EMAIL,
)
还有风景
from django.conf import settings
from django.http import HttpResponse
def exception(request, traceback_name):
traceback_path = os.path.join(settings.EXCEPTIONS_DIR, traceback_name)
with open(traceback_path, 'r') as f:
response = HttpResponse(f.read())
return response
完整的中间件是根据我们的需求量身定制的,但基础知识就在那里。您可能应该以某种方式使用密码保护视图。除非您返回响应,否则 Django 自己的错误处理将启动并仍然向您发送电子邮件,但我会留给您。