from logging import Formatter, Handler, StreamHandler, getLogger from django.conf import settings from django.core.mail import mail_admins # Define LOG_FORMAT and LOG_ROOTS in your settings.py file. # LOG_FORMAT is used for formatting error messages: see http://docs.python.org/lib/node406.html # LOG_ROOTS is an iterable of root logger names that will be caught by this handler. class RequestFormatter (Formatter): def __init__ (self, print_request = True): # logging.Formatter is an old-style class Formatter.__init__ (self, settings.LOG_FORMAT) self.__print_request = print_request def format (self, record): message = Formatter.format (self, record) if self.__print_request: try: request_repr = repr (record.request) except Exception: request_repr = "Request repr() unavailable" message += "\n\n" message += request_repr return message class MailAdminsHandler (Handler): def get_subject (self, record): try: request = record.request except AttributeError: return "Error (no request attached)" if request.META.get ('REMOTE_ADDR') in settings.INTERNAL_IPS: remote_attr = "internal" else: remote_attr = "EXTERNAL" return "Error (%s IP): %s" % (remote_attr, request.path) def emit (self, record): subject = self.get_subject (record) message = self.format (record) mail_admins (subject, message, fail_silently = True) class LoggingSetupMiddleware (object): def __init__ (self): if settings.DEBUG: handler = StreamHandler () formatter = RequestFormatter (print_request = False) else: handler = MailAdminsHandler () formatter = RequestFormatter (print_request = True) handler.setFormatter (formatter) for root_name in settings.LOG_ROOTS: getLogger (root_name).addHandler (handler)