Jan 30, 2012

Logging

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)

No comments: