Skip to content

Instantly share code, notes, and snippets.

@philfreo
Created November 20, 2012 06:36
Show Gist options
  • Save philfreo/4116416 to your computer and use it in GitHub Desktop.
Save philfreo/4116416 to your computer and use it in GitHub Desktop.
Flask detailed error emails
from logging.handlers import SMTPHandler
class DetailedSMTPHandler(SMTPHandler):
def __init__(self, app_name, *args, **kwargs):
self.app_name = app_name
return super(DetailedSMTPHandler, self).__init__(*args, **kwargs)
def getSubject(self, record):
from flask import request
from socket import gethostname
error = 'Error'
ei = record.exc_info
if ei:
error = '(%s) %s' % (ei[0].__name__, ei[1])
return "[%s] %s %s on %s" % (self.app_name, request.path, error, gethostname())
def emit(self, record):
"""
Emit a record.
Format the record and send it to the specified addressees.
"""
try:
import smtplib
from email.utils import formatdate
from flask import request
port = self.mailport
if not port:
port = smtplib.SMTP_PORT
smtp = smtplib.SMTP(self.mailhost, port)
msg = self.format(record)
msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s\n\nRequest.url: %s\n\nRequest.headers: %s\n\nRequest.args: %s\n\nRequest.form: %s\n\nRequest.data: %s\n" % (
self.fromaddr,
",".join(self.toaddrs),
self.getSubject(record),
formatdate(), msg, request.url, request.headers, request.args, request.form, request.data)
if self.username:
if self.secure is not None:
smtp.ehlo()
smtp.starttls(*self.secure)
smtp.ehlo()
smtp.login(self.username, self.password)
smtp.sendmail(self.fromaddr, self.toaddrs, msg)
smtp.quit()
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
# Error emails
if not app.debug:
import logging
from flask.ext.common.utils import DetailedSMTPHandler
mail_handler = DetailedSMTPHandler(config['APPLICATION_NAME'], (config['ERROR_MAIL_SERVER'], config['ERROR_MAIL_PORT']),
config['SERVER_EMAIL'],
config['ADMINS'],
'Server error',
(config['ERROR_MAIL_USERNAME'], config['ERROR_MAIL_PASSWORD']),
secure=config['ERROR_MAIL_USE_TLS'] and ())
mail_handler.setLevel(logging.ERROR)
app.logger.addHandler(mail_handler)
mail_handler.setFormatter(logging.Formatter('''\
Message type: %(levelname)s
Location: %(pathname)s:%(lineno)d
Module: %(module)s
Function: %(funcName)s
Time: %(asctime)s
Message:
%(message)s
'''))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment