Archive

Posts Tagged ‘logging’

Logging with Python (Part 2)

August 5, 2013 Leave a comment

This post is just a placeholder for Logbook that I haven’t investigated yet (TODO).

Until I write more about it, here is an example that uses it.

Categories: python Tags: ,

Logging with Python (Part 1)

August 5, 2013 Leave a comment

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:
Design a site like this with WordPress.com
Get started