Saturday, April 5, 2008

Logging (I'm no lumberjack, but I'm okay)

Exploring the Python standard library is fun.

Not long ago I found how great the logging module is. Use it to create a logging channel, attach different handlers to it (for logging events to a file, through email or HTTP, etc), then make one-line log events of different types.

import logging
import logging.handlers

# Sets up a basic textfile log, with formatting
format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%m/%d/%y %H:%M:%S',

# Log a few different events'Just testing the water.')
logging.warning('Hmm, something is not right here')
logging.error("Oh no, now you're in for it")
The resulting text log:
02/14/08 22:19:03 INFO     Just testing the water.
02/14/08 22:19:03 WARNING Hmm, something is not right here
02/14/08 22:19:03 ERROR Oh no, now you're in for it
Add a few more lines and it sends you an email for any logs that are level "ERROR" or above:

email = logging.handlers.SMTPHandler('',
'',(''),'Error Report')

There's several other handler types as well. Very useful!