Rob Wolfe
1/17/2008 7:47:00 PM
DwBear75 <dwbear75@gmail.com> writes:
> I am hoping to find some simple examples of how to create a logger
> instance using smtphandler. I don't want to create a separate ini
> file. I just want to sent the smtphost, from, to right in the code
> when I instantiate the logger. I can't seem to find simple code on how
> to do this. Any pointers ?
If you need to use smtp authentication there is a small problem
with `SMTPHandler`. Actually, you need to subclass `SMTPHandler`
and override `emit` method, e.g.:
from logging import getLogger, Formatter, DEBUG
from logging.handlers import SMTPHandler
class SMTPAuthHandler(SMTPHandler):
def __init__(self, mailhost, fromaddr, toaddrs, subject,
user=None, password=None):
SMTPHandler.__init__(self, mailhost, fromaddr, toaddrs, subject)
self.user = user
self.password= password
def emit(self, record):
import smtplib
from email.Utils import formatdate
smtp = smtplib.SMTP(self.mailhost, smtplib.SMTP_PORT)
if self.user and self.password:
smtp.login(self.user, self.password)
msg = self.format(record)
msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % (
self.fromaddr,
','.join(self.toaddrs),
self.getSubject(record),
formatdate(), msg)
smtp.sendmail(self.fromaddr, self.toaddrs, msg)
smtp.quit()
def smtp_logger(level, mailhost, fromaddr, toaddr, subject,
user=None, password=None):
logger = getLogger('AppName')
logger.setLevel(level)
hdlr = SMTPAuthHandler(mailhost, fromaddr, toaddr, subject,
user, password)
fmt = Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
'%Y-%m-%d %H:%M:%S')
hdlr.setFormatter(fmt)
logger.addHandler(hdlr)
hdlr.setLevel(level)
return logger
logger = smtp_logger(DEBUG, 'mailhost', 'fromaddr', 'toaddr',
'DEBUG: AppName', 'user', 'password')
logger.debug('some message')
HTH,
Rob