Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually trigger Django email error report

Django error reporting handles uncaught exceptions by sending an email, and (optionally) shows user a nice 500 error page.

This works very well, but in a few instances I'd like to allow users to continue with their business uninterrupted, but still have Django send me the email error report about the exception.

So basically: can I manually send email error report even if I catch the exception?

Of course, I'd like to avoid manually generating the error report email.

like image 771
frnhr Avatar asked Apr 01 '15 13:04

frnhr


People also ask

How do I send an email using Django?

In most cases, you can send email using django. core. mail. send_mail() .

What is Server error 500 in Django?

When DEBUG is False , Django will email the users listed in the ADMINS setting whenever your code raises an unhandled exception and results in an internal server error (strictly speaking, for any response with an HTTP status code of 500 or greater). This gives the administrators immediate notification of any errors.

How do I create a custom exception in Django REST framework?

Custom exception handlingThe exception handler function should either return a Response object, or return None if the exception cannot be handled. If the handler returns None then the exception will be re-raised and Django will return a standard HTTP 500 'server error' response.

How does Django integrate with email?

Sending Emails with the Django Shell We import the Django send_mail function. Then we import the settings object which contains all the global settings and the per-site settings (those inside the settings.py file). Finally, we pass all the needed arguments to the send_mail function.


2 Answers

You can use the following code to send manually an email about a request and an exception e:

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()     ) 

You can test it in a view like this:

def test_view(request):     try:         raise Exception     except Exception as e:         send_manually_exception_email(request, e) 
like image 76
JuniorCompressor Avatar answered Sep 29 '22 09:09

JuniorCompressor


Just setup a simple log handler in your settings.

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'         },         'app': {             'level': 'ERROR',             'filters': ['require_debug_false'],             'class': 'django.utils.log.AdminEmailHandler'         },     },     'loggers': {         'django.request': {             'handlers': ['mail_admins'],             'level': 'ERROR',             'propagate': True,         },     } } 

and then in your view, you can do anything

 import logging  logger = logging.getLogger('app')   def some_view(request):      try:          # something          if something_wnet_wrong:              logger.error('Something went wrong!')          return some_http_response      except:          #something else          logger.error(sys.exc_info(), request)                  return some_other_response 

If you want detailed error report, you can try something like this.

You also need to take care of sensitive information.

like image 34
Pandikunta Anand Reddy Avatar answered Sep 29 '22 11:09

Pandikunta Anand Reddy