两种比较简单的方式:
①使用settings.LOGGING日志配置
②使用自定义中间件(实际上是使用中间件钩子:process_exception())
①LOGGING配置实现:
# 配置提示邮件发送的ADMINS
ADMINS = [('your_name', 'example@email.com')]
# 配置EMAILBACKEND
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.163.com' # 此处替换成自己的邮件的主机
EMAIL_PORT = 25
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False
EMAIL_HOST_USER = '******@email.com'
EMAIL_HOST_PASSWORD = '*************'
# DEFAULT_FROM_EMAIL = '******@email.com'
# 配置日志配置
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
# ***************当DEBUG=False时开启***************
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse',
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler',
},
},
"loggers": {
"django.request": {
"handlers": ["mail_admins"],
"level": "ERROR", # 错误级别Error以上
"propagate": True,
},
}
②自定义中间件实现(自定义中间件钩子:process_exception()):
import traceback
from django.conf import settings
from django.utils import timezone
from django.core.mail import EmailMultiAlternatives
# 自定义中间件
class RequestTimerMiddleware:
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):
# 在DEBUG=False时启用
if not settings.DEBUG:
# 此处也可以对exception进行类型判断,对不同类型进行不同的处理
subject = f'Error on {request.path}'
message = f'Exception type: {type(exception).__name__}\n\n'
message += f'Exception message: {str(exception)}\n\n'
message += 'Traceback:\n'
message += ''.join(traceback.format_exception(None, exception, exception.__traceback__))
to = ['to@email.com'] # 收件人邮箱列表
email = EmailMultiAlternatives(subject=subject, body=message, from_email=settings.EMAIL_HOST_USER, to=to)
# 当然也可以给你的邮件加点花样,比如:使用模板文件
email.send()
# 返回 None 或 HttpResponse 对象
return None
# 最后将自定义的中间件添加到settings.py的MIDDLEWARE配置中
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'your_app.your_file.RequestTimerMiddleware' # 自定义中间件
]
个人理解,不同意就当鄙人放了个屁