Logging in Python

Posted: 28th November 2012 by knoppi in Computer Stuff, Programming
Tags: , ,

I am an excessive user of the built-in logging facilities of Python. Most information about that topic can be found in the Python Logging Howto or in the description of the logging module. If you’re interested how I use it in my modules, just go on reading

Nearly every piece of python code I write contains the following (adopted) lines:

import logging

module_logger = logging.getLogger("some funny name")
module_logger.propagate = False

formatter = logging.Formatter(
fmt = "%(asctime)s -- %(name)s -- %(levelname)s -- %(message)s" )

ch = logging.StreamHandler()
ch.setFormatter(formatter)
ch.setLevel(logging.WARNING)

module_logger.addHandler(ch)
module_logger.setLevel(logging.WARNING)

def set_debug_level(level):
possible_levels = dict(
debug = logging.DEBUG, info = logging.INFO,
warning = logging.WARNING, error = logging.ERROR,
fatal = logging.FATAL)
ch.setLevel(possible_levels[level])
module_logger.setLevel(possible_levels[level])

So that’s it. My policy is to use mainly debug and info as the output level where the distinction lies in the amount of data a logging call produces. Information about steps in long iterations always is on debug level. Logging for methods which tend to be called very often is also mainly debug, while, e.g., constructors produce info-output. You see that by default I get no output at all as the predefined level is WARNING, which be the set_debug_level method of the module can be adjusted.

BTW: I just realized that the code tag of WordPress within this style spoils whitespaces, which is especially bad for Python. I’m going to figure this out as soon as possible.