有一个 django 模板变量TECHNICAL_500_TEMPLATE
/TECHNICAL_500_TEXT_TEMPLATE
in the Django 调试视图 https://github.com/django/django/blob/1.9.5/django/views/debug.py它控制错误报告中可见的内容,当然还有错误电子邮件。注释解释说模板位于 python 变量中,因此在模板加载器中断时可能会生成错误。您可以在 django 包中更改此变量,但我不建议这样做。TECHNICAL_500_TEMPLATE
被引用的是ExceptionReporter
类在同一个文件中。
班上AdminEmailHandler
in Django 实用程序日志 https://github.com/django/django/blob/1.9.5/django/utils/log.py然后使用ExceptionReporter
生成 html 错误报告。
你可以子类化AdminEmailHandler
并覆盖emit
函数包含您的子类版本ExceptionReporter
使用您自己定义的TECHNICAL_500_TEMPLATE
.
这是一个例子:
Create reporter.py
with
from copy import copy
from django.views import debug
from django.utils import log
from django.conf import settings
from django import template
TECHNICAL_500_TEMPLATE = """
# custom template here, copy the original and make adjustments
"""
TECHNICAL_500_TEXT_TEMPLATE = """
# custom template here, copy the original and make adjustments
"""
class CustomExceptionReporter(debug.ExceptionReporter):
def get_traceback_html(self):
t = debug.DEBUG_ENGINE.from_string(TECHNICAL_500_TEMPLATE)
c = template.Context(self.get_traceback_data(), use_l10n=False)
return t.render(c)
def get_traceback_text(self):
t = debug.DEBUG_ENGINE.from_string(TECHNICAL_500_TEXT_TEMPLATE)
c = template.Context(self.get_traceback_data(), autoescape=False, use_l10n=False)
return t.render(c)
class CustomAdminEmailHandler(log.AdminEmailHandler):
def emit(self, record):
try:
request = record.request
subject = '%s (%s IP): %s' % (
record.levelname,
('internal' if request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS
else 'EXTERNAL'),
record.getMessage()
)
except Exception:
subject = '%s: %s' % (
record.levelname,
record.getMessage()
)
request = None
subject = self.format_subject(subject)
no_exc_record = copy(record)
no_exc_record.exc_info = None
no_exc_record.exc_text = None
if record.exc_info:
exc_info = record.exc_info
else:
exc_info = (None, record.getMessage(), None)
reporter = CustomExceptionReporter(request, is_email=True, *exc_info)
message = "%s\n\n%s" % (self.format(no_exc_record), reporter.get_traceback_text())
html_message = reporter.get_traceback_html() if self.include_html else None
self.send_mail(subject, message, fail_silently=True, html_message=html_message)
然后只需设置 django 设置即可在中使用新处理程序记录部分 https://docs.djangoproject.com/en/1.9/topics/logging/.
LOGGING = {
# Your other logging settings
# ...
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'project.reporter.CustomAdminEmailHandler',
'filters': ['special']
}
},
}
如果您只是想隐藏设置,可以注释掉'settings': get_safe_settings(),
第 294 行,如果您覆盖并复制粘贴def get_traceback_data(self):
在你的CustomExceptionReporter