Adding basic logging to your Python script

Whether you like it or not, but there are many situations when you need to add logging information. It is easy to start with some print statements, but what if at certain point you want to put this information to a file? Redirecting output to a file will result in all-or-nothing situation since the contents of the file will be only visible at the end of execution. A more flexible and proper solution would be using a proper logging module.

To start off with

import logging

LOG_FORMAT = '%(asctime)s [%(levelname)s] %(message)s'
logging.basicConfig(format = LOG_FORMAT, level=logging.DEBUG)
log = logging.getLogger(__name__)

And then instead of a print statement you can use the following statements:

log.debug('debug string')
log.info('info string')
log.error('error string')

which will result in

2014-03-01 20:27:19,314 [DEBUG] debug message
2014-03-01 20:27:32,900 [INFO] info string
2014-03-01 20:28:19,472 [ERROR] error string

Enjoy!