Writing a middleware to log all error messages in django

< 1 min read

Few days back I was given to implement a logging system that will send all critical error message in the system to admin emails. And i was given only 2 hours. I have written a middle ware for that purpose.

Here is the middle ware code:

from core.library.email_scheduler import EmailScheduler
from core.library.email_template_util import EmailTemplateUtil

__author__ = 'Sohel'
from django.conf import settings
from django import http
from django.core.mail import mail_admins

import sys
import traceback

# Temporary, from http://code.djangoproject.com/attachment/ticket/6094/6094.2008-02-01.difffrom django.core.urlresolvers import RegexURLResolver
def resolver(request):
    """    Returns a RegexURLResolver for the request's urlconf.
    If the request does not have a urlconf object, then the default of    settings.ROOT_URLCONF is used.    """    from django.conf import settings
    urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)
    return RegexURLResolver(r'^/', urlconf)


class ExceptionHandleMiddleware(object):
    def process_exception(self, request, exception):
        self.handle_500(request, exception)


    def handle_500(self, request, exception):
        try:
            exc_info = traceback.format_exc()
            html, text = EmailTemplateUtil.render_internal_server_error_admin_email(exc_info)
            recipients = []
            for admin in settings.ADMINS:
                recipients += [ admin[1] ]
            email_object = {
                "recipients": recipients,                'subject': 'Internal Server Error Occured',                'html_body': html,                'text_body': text
            }

            EmailScheduler.place_to_queue(email_object)
        except Exception,msg:
            print("Exception occured while sending emails to admins.")


    def exception_email(self, request, exc_info):
        subject = 'Error (%s IP): %s' % ((request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS and 'internal' or 'EXTERNAL'), request.path)
        try:
            request_repr = repr(request)
        except:
            request_repr = "Request repr() unavailable"        message = "%s\n\n%s" % (_get_traceback(exc_info), request_repr)
        return subject, message


    def log_exception(self, request, exception, exc_info):
        subject, message = self.exception_email(request, exc_info)
        mail_admins(subject, message, fail_silently=True)

Leave a Reply

Your email address will not be published.