服务器错误时,邮件请求正文以及Django Admin

时间:2016-03-08 13:08:39

标签: python django python-2.7 django-admin tastypie

我在Django中使用默认记录器,具有以下配置:

LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
    '()': 'django.utils.log.RequireDebugFalse'
    }
},
'handlers': {
    'mail_admins': {
        'level': 'ERROR',
        'filters': ['require_debug_false'],
        'class': 'django.utils.log.AdminEmailHandler'
    },
    'console': {
        'level': 'DEBUG',
        'class': 'logging.StreamHandler'
    }
},
'loggers': {
    'django.request': {
        'handlers': ['mail_admins', 'console'],
        'level': 'ERROR',
        'propagate': True,
    },
}

}

因此,每当我收到500错误时,我正确地收到管理员电子邮件ID中的邮件,但它没有发送POST请求JSON数据。我发送的请求如下:

curl -X POST -H 'Content-Type: application/json'  http://127.0.0.1/api/customer/ -d "{'username':'rajeevnith', 'frist_name': 'Rajeev', 'last_name':'Bahrdwaj'}"

我们如何配置django logger以发送此请求正文?

2 个答案:

答案 0 :(得分:0)

我们使用这样的管理电子邮件处理程序,适用于任何类型的错误。希望对你有效。

class MyAdminEmailHandler(AdminEmailHandler):

    def __init__(MyAdminEmailHandler, include_html=False, email_backend=None):
        super(MyAdminEmailHandler, self).__init__(self, include_html, email_backend)

    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{0}'.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

        try:
            mail.mail_admins(subject, message, fail_silently=True,
                             html_message=html_message,
                             connection=self.connection())
        except Exception as e:
            console_logger.warn("%s : %s" % (__name__, str(e)))

答案 1 :(得分:0)

从Django v3.1开始,一种方法(可能是最快的方法)是将您的类简单地添加到settings.py

DEFAULT_EXCEPTION_REPORTER = 'package.log.CustomExceptionReporter'

,然后在log.py中:

class CustomExceptionReporter(ExceptionReporter):
    def get_traceback_data(self):
        data = super().get_traceback_data()
        
        #remove settings
        del data['settings']
        
        #add body if it exists
        if self.request is not None:
            if self.request.method == "POST":
                try:
                    data['request_body'] = request.body
                except:
                    data['request_body'] = None
                
            
        return data