Home > python > Logging with Python (Part 1)

Logging with Python (Part 1)

Problem
You have used print statements in your programs to print debug information, but you would like to start using the logging module too. You want to log to the stdout, you want to log to a file, or you want to log to BOTH places (stdout and file).

Solution
The following entry is based on this post.

Our customized logging module (mylogging.py):

import logging
import sys

DEBUG_LOG_FILENAME = "jabba.log"

# set up formatting
formatter = logging.Formatter("%(levelname)-5s %(asctime)s %(module)s.%(funcName)s() [%(lineno)d]: %(message)s", "%Y-%m-%d %H:%M:%S")

# set up logging to STDOUT for all levels DEBUG and higher
sh = logging.StreamHandler(sys.stdout)
sh.setLevel(logging.DEBUG)
sh.setFormatter(formatter)

# set up logging to a file for all levels DEBUG and higher
fh = logging.FileHandler(DEBUG_LOG_FILENAME)
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)

# create Logger object
mylogger = logging.getLogger('MyLogger')
mylogger.setLevel(logging.DEBUG)
mylogger.addHandler(sh)    # enabled: stdout
mylogger.addHandler(fh)    # enabled: file

# create shortcut functions
debug = mylogger.debug
info = mylogger.info
warning = mylogger.warning
error = mylogger.error
critical = mylogger.critical

To enable/disable logging to stdout / file, just comment/uncomment these two lines:

mylogger.addHandler(sh)    # enabled: stdout
mylogger.addHandler(fh)    # enabled: file

And now a test file to demonstrate its usage:

#!/usr/bin/env python

from mylogging import debug, info, warning

def main():
    for i in xrange(100):
        if i % 5 == 0:
            info("i is {i}".format(i=i))
        if i % 50 == 0:
            debug("i is {i}".format(i=i))
        if i % 99 == 0:
            warning("i is {i}".format(i=i))

#############################################################################

if __name__ == "__main__":
    main()

Credits
Thanks to SaltyCrane for his excellent blog post on the topic.

Categories: python Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: