Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mail request body as well to Django Admin while server error

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 ?

like image 879
r.bhardwaj Avatar asked Mar 08 '16 13:03

r.bhardwaj


1 Answers

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
like image 58
mrj Avatar answered Nov 02 '22 10:11

mrj