在Django中向admin发送错误邮件

时间:2017-10-29 20:28:12

标签: django django-email

我正在尝试在django中发生任何异常时向ADMIN发送邮件。所以我尝试但无法找到解决方案。我不清楚如何向管理员发送错误邮件 任何帮助将不胜感激。

Views.py

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()
        )
        filter = get_exception_reporter_filter(request)
        request_repr = '\n{}'.format(force_text(filter.get_request_repr(request)))
    except Exception:
        subject = '%s: %s' % (
            record.levelname,
            record.getMessage()
        )
        request = None
        request_repr = "unavailable"
    subject = self.format_subject(subject)

    if record.exc_info:
        exc_info = record.exc_info
    else:
        exc_info = (None, record.getMessage(), None)

    message = "%s\n\nRequest repr(): %s" % (self.format(record), request_repr)
    reporter = ExceptionReporter(request, is_email=True, *exc_info)
    html_message = reporter.get_traceback_html() if self.include_html else None
    self.send_mail(subject, message, fail_silently=True, html_message=html_message)

def send_mail(self, subject, message, *args, **kwargs):
    mail.mail_admins(subject, message, *args, connection=self.connection(), **kwargs)


def connection(self):
    return get_connection(backend=self.email_backend, fail_silently=True)

def format_subject(self, subject):
    """
    Escape CR and LF characters, and limit length.
    RFC 2822's hard limit is 998 characters per line. So, minus "Subject: "
    the actual subject must be no longer than 989 characters.
    """
    formatted_subject = subject.replace('\n', '\\n').replace('\r', '\\r')
    return formatted_subject[:989]

def test_view(request):
    try:
        raise Exception
    except Exception as e:
        send_mail(self, subject, message, *args, **kwargs)

logger_setting.py

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse',
        },
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },
    'handlers': {
        'console': {
            'level': 'INFO',
            'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
        },
        'null': {
            'class': 'logging.NullHandler',
        },
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
        },
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': False,
        },
        'django.security': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': False,
        },
        'py.warnings': {
            'handlers': ['console'],
        },
    }
}

我还试过更改我的view.py代码如下,但没有任何错误邮件

import sys
import traceback
from django.core import mail
from django.views.debug import ExceptionReporter

def send_manually_exception_email(request, e):
    exc_info = sys.exc_info()
    reporter = ExceptionReporter(request, is_email=True, *exc_info)
    subject = e.message.replace('\n', '\\n').replace('\r', '\\r')[:989]
    message = "%s\n\n%s" % (
        '\n'.join(traceback.format_exception(*exc_info)),
        reporter.filter.get_request_repr(request)
    )
    mail.mail_admins(
        subject, message, fail_silently=True,
        html_message=reporter.get_traceback_html()
    )

生成测试例外 -

def test_view(request):
    try:
        raise Exception
    except Exception as e:
        send_manually_exception_email(request, e)

1 个答案:

答案 0 :(得分:1)

首先按照以下说明操作:https://docs.djangoproject.com/en/1.11/howto/error-reporting/#email-reports

并设置EMAIL_HOST,EMAIL_HOST_USER,EMAIL_HOST_PASSWORD,ADMINS和SERVER_EMAIL的设置。

您还需要设置电子邮件服务器。对于初学者来说,其中任何一个都可以:

  • 电子邮件程序(如sendmail)
  • 电子邮件服务器(如Sendgrid)
  • python调试电子邮件服务器python -m smtpd -n -c DebuggingServer localhost:1025

您的设置值必须与您选择的电子邮件服务器匹配。

在您首先从设置中配置简单案例之前,请不要担心使用电子邮件进行日志记录。