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
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%m/%d/%y %H:%M:%S',
filename=r'C:\temp\mylog.log',
filemode='a')

# Log a few different events
logging.info('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('smtp.foo.com',
'script@foo.com',('techart@bar.com'),'Error Report')
email.setLevel(logging.ERROR)

logging.getLogger('').addHandler(email)
There's several other handler types as well. Very useful!

No comments: