Skip to content

Instantly share code, notes, and snippets.

@jfialkoff
Last active December 19, 2015 09:08
Show Gist options
  • Save jfialkoff/5930324 to your computer and use it in GitHub Desktop.
Save jfialkoff/5930324 to your computer and use it in GitHub Desktop.
This is an email handler like Django's built-in email hander that allows you to optionally send emails to admins even if it's lower priority than ERROR. You can also include additional content in the email. For example, logging.info('Something happened.', extra={'tell_admins': True, 'email_content': 'Some more info to put in the email.'})
import logging
import traceback
from django.conf import settings
from django.core import mail
from django.utils.log import AdminEmailHandler
from django.views.debug import ExceptionReporter
from django.views.debug import get_exception_reporter_filter
from .str_tools import strjoin
class SuperAdminEmailHandler(AdminEmailHandler):
def emit(self, record):
tell_admins = getattr(record, 'tell_admins', False)
content = getattr(record, 'email_content', '')
if record.levelno < logging.ERROR and not tell_admins:
return
try:
request = record.request
subject = '%s (%s IP): %s' % (
record.levelname,
(request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS
and 'internal' or 'EXTERNAL'),
record.getMessage()
)
filter = get_exception_reporter_filter(request)
request_repr = filter.get_request_repr(request)
except Exception:
subject = '%s: %s' % (
record.levelname,
record.getMessage()
)
request = None
request_repr = "Request repr() unavailable."
subject = self.format_subject(subject)
if record.exc_info:
exc_info = record.exc_info
stack_trace = '\n'.join(traceback.format_exception(*record.exc_info))
else:
exc_info = (None, record.getMessage(), None)
stack_trace = 'No stack trace available'
message = strjoin(content, stack_trace, request_repr, delim='\n\n')
reporter = ExceptionReporter(request, is_email=True, *exc_info)
html_message = self.include_html and reporter.get_traceback_html() or None
mail.mail_admins(subject, message, fail_silently=True, html_message=html_message)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment