logging multiple messages

Daniel daniel.watrous at gmail.com
Thu Jan 15 18:00:56 EST 2009


I was fighting with a problem all day that was producing multiple
messages in my logging output.  The problem was related to the fact
that I was defining logging handlers multiple times.  I found the
following posting from a few years ago that related to my problem:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/8a707c289642c668/44f16cf5ba68721f?lnk=gst&q=logging#44f16cf5ba68721f

What I did was the following:

def initLogging(loggingArea):
    # create/get logger
    logger = logging.getLogger("mylogger")
    logger.setLevel(logging.DEBUG)

    # setup Handlers
    if len(logger.handlers) == 0:
        # create handlers only if there are none
        sh = logging.StreamHandler()
        # now add the handlers
        logger.addHandler(sh)

If the logger already has handlers nothing happens, otherwise they're
created and added to the logger.  Now I can call initLogging
('mylogarea') whereever I need to without getting multiple messages.

If you know of a better way to do this let me know...



More information about the Python-list mailing list