Mail request body as well to Django Admin while server error
Asked Answered
G

2

10

I am using default logger in Django having following configuration:

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,
    },
}

}

So whenever I am getting 500 error I am correctly getting the mails in admin email id but it is not sending the POST request JSON data. I am sending the request as below:

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

How can we configure django logger to send this request body as well ?

Gilgai answered 8/3, 2016 at 13:8 Comment(6)
you might want to look at this https://mcmap.net/q/1169081/-simple-error-log-message-in-djangoConstantina
Does it really not log the request? I have a very, very similar default logging setup and I see the entire request object in my logs. The Django docs even indicate that the request object is logged using the extra argument: docs.djangoproject.com/ja/1.9/topics/logging/#django-request which indicates to me that either you are just not seeing it and its there, or you have something overwritten somewhere in your code to make it not behave the way it was built.Rosalynrosalynd
@TitusP No, its not sending whole request objects. It is only sending request.GET, request.POST, request. FILES, request.COOKIES and request.META whereas while posting the data in Content-Type: application/json, the data comes in request.bodyGilgai
Django version?Defalcation
@EllaShar 1.9.7Gilgai
I'm not very familiar with curl, but I think the URL should be the last parameter. So maybe you're not sending any POST data at all?Defalcation
E
1

As of Django v3.1 one way (probably the fastest) is to simply add your class to your settings.py:

DEFAULT_EXCEPTION_REPORTER = 'package.log.CustomExceptionReporter'

and then in 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
Electrophorus answered 11/9, 2020 at 20:45 Comment(0)
E
0

we use an admin email handler like this, which works for any type of error. hope it works for you.

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)))
Erroneous answered 11/11, 2016 at 16:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.