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:

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__
                # 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:

import logging
import logging.handlers
import smshandler

# Create a logging object (after configuring logging)
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

# and finally we add the handler to the logging object

# And finally a test
logger.debug('Test 1')'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