import logging import logging.handlers import types # The SMTPHandler taken from python 2.6 class SMTPHandler(logging.Handler): """ A handler class which sends an SMTP email for each logging event. """ def __init__(self, mailhost, fromaddr, toaddrs, subject, credentials=None): """ Initialize the handler. Initialize the instance with the from and to addresses and subject line of the email. To specify a non-standard SMTP port, use the (host, port) tuple format for the mailhost argument. To specify authentication credentials, supply a (username, password) tuple for the credentials argument. """ logging.Handler.__init__(self) if type(mailhost) == types.TupleType: self.mailhost, self.mailport = mailhost else: self.mailhost, self.mailport = mailhost, None if type(credentials) == types.TupleType: self.username, self.password = credentials else: self.username = None self.fromaddr = fromaddr if type(toaddrs) == types.StringType: toaddrs = [toaddrs] self.toaddrs = toaddrs self.subject = subject def getSubject(self, record): """ Determine the subject for the email. If you want to specify a subject line which is record-dependent, override this method. """ return self.subject weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] monthname = [None, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] def date_time(self): """ Return the current date and time formatted for a MIME header. Needed for Python 1.5.2 (no email package available) """ year, month, day, hh, mm, ss, wd, y, z = time.gmtime(time.time()) s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % ( self.weekdayname[wd], day, self.monthname[month], year, hh, mm, ss) return s def emit(self, record): """ Emit a record. Format the record and send it to the specified addressees. """ try: import smtplib try: from email.utils import formatdate except ImportError: formatdate = self.date_time port = self.mailport if not port: port = smtplib.SMTP_PORT smtp = smtplib.SMTP(self.mailhost, port) msg = self.format(record) msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % ( self.fromaddr, string.join(self.toaddrs, ","), self.getSubject(record), formatdate(), msg) if self.username: smtp.login(self.username, self.password) smtp.sendmail(self.fromaddr, self.toaddrs, msg) smtp.quit() except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record) # Monkey patch logging.handlers logging.handlers.SMTPHandler = SMTPHandler