Custom handler for Python's logging module

Posted by mikael on 2009-08-30 00:43, section: Software

After spending some time messing with Python's logging module at work I decided to create a new handler for it, this was mainly to clean up my code a bit (and so I wouldn't have to manually call a custom module for sending SMS). Since there appears to be little info online about how to easily create a new handler I've decided to share my approach.

We start off with the actual handler, or a simplified version anyway:

# smshandler.py
import logging
import sendsms # our internal module for sending SMS

class SMSHandler(logging.Handler): # Inherit from logging.Handler
        def __init__(self, phonenumber):
                # run the regular Handler __init__
                logging.Handler.__init__(self)
                # Our custom argument
                self.phonenumber = phonenumber
        def emit(self, record):
                # record.message is the log message
                sendsms.send(self.phonenumber, record.message)

Now, the above code is pretty useless on its own, we need to use it:

# handlertest.py
import logging
import logging.handlers
import smshandler

# Create a logging object (after configuring logging)
logging.basicConfig(filename=LOG_FILENAME,level=logging.WARNING)
logger = logging.getLogger()

# A little trickery because, at least for me, directly creating
# an SMSHandler object didn't work
logging.handlers.SMSHandler = smshandler.SMSHandler

# create the handler object
testHandler = logging.handlers.SMSHandler('46701234567')
# Configure the handler to only send SMS for critical errors
testHandler.setLevel(logging.CRITICAL)

# and finally we add the handler to the logging object
logger.addHandler(testHandler)

# And finally a test
logger.debug('Test 1')
logger.info('Test 2')
logger.warning('Test 3')
logger.error('Test 4')
logger.critical('Test 5')

If we were to run this script then the only message that would be sent as an SMS would be the last one, 'Test 5'. And this code is simple enough that I doubt anyone using the logging module would have little trouble adapting it to whatever non-standard method of logging they want to employ.

blog comments powered by Disqus