Learning Python Network Programming

(Sean Pound) #1
Chapter 4
self.setFormatter(logging.Formatter("%(asctime)s
%(levelname)-5s %(message)s"))

def flush(self):
if len(self.buffer) > 0:
try:
import smtplib
port = self.mailport
if not port:
port = smtplib.SMTP_PORT
smtp = smtplib.SMTP(self.mailhost, port)
msg = "From: %s\r\nTo: %s\r\nSubject:
%s\r\n\r\n" % (self.fromaddr,
",".join(self.toaddrs), self.subject)
for record in self.buffer:
s = self.format(record)
print(s)
msg = msg + s + "\r\n"
smtp.sendmail(self.fromaddr, self.toaddrs, msg)
smtp.quit()
except:
self.handleError(None) # no particular record
self.buffer = []

def test():
logger = logging.getLogger("")
logger.setLevel(logging.DEBUG)
logger.addHandler(BufferingSMTPHandler(MAILHOST, FROM, TO,
SUBJECT, 10))
for data in ['First', 'Second', 'Third', 'Fourth']:
logger.info("%s line of log", data)
logging.shutdown()

if __name__ == "__main__":
test()

As you can see, our BufferingSMTPHandler method only overrides one method,
that is, flush(). On the constructor, init(), the basic variable is setup as well
as the logging format by using the setFormatter() method. In the flush() method,
we have created an instance of an SMTP() object. The SMTP message header has
been created by using the data available. The log message has been appended to
the e-mail message, and the sendmail() method has been called to send the e-mail
message. The code in the flush() method is wrapped inside a try-except block.

Free download pdf