Learning Python Network Programming

(Sean Pound) #1

Engaging with E-mails


Sending e-mails via the logging module


In any modern programming language, the logging facilities are provided with
common features. Similarly, Python's logging module is very rich in features and
flexibilities. We can use the different types of log handlers with the logging module,
such as the console or the file logging handler. One way in which you can maximize
your logging benefits is by e-mailing the log messages to the user just as the log
is being produced. Python's logging module provides a type of handler called
BufferingHandler, which is capable of buffering the log data.


An example of extending BufferingHandler has been displayed later. A child class
called BufferingSMTPHandler is defined by BufferingHandler. In this example,
an instance of the logger object is created by using the logging module. Then, an
instance of BufferingSMTPHandler is tied to this logger object. The logging level is
set to DEBUG so that it can log any message. A sample list of four words has been
used for creating the four log entries. Each log entry should resemble the following:


INFO First line of log

This accumulated log message will be emailed to a local user as set
on top of the script.


Now, let us take a look at the full code. The following is an example of sending an
e-mail with the help of the logging module:


import logging.handlers
import getpass

MAILHOST = 'localhost'
FROM = 'you@yourdomain'
TO = ['%s@localhost' %getpass.getuser()]
SUBJECT = 'Test Logging email from Python logging module
(buffering)'

class BufferingSMTPHandler(logging.handlers.BufferingHandler):
def __init__(self, mailhost, fromaddr, toaddrs, subject,
capacity):
logging.handlers.BufferingHandler.__init__(self, capacity)
self.mailhost = mailhost
self.mailport = None
self.fromaddr = fromaddr
self.toaddrs = toaddrs
self.subject = subject
Free download pdf