Help me with weird logging problem

J dreadpiratejeff at gmail.com
Tue Mar 6 11:09:23 EST 2012


Hi,

I'm trying to add a couple log handlers to a program.  The end goal is
to log things at INFO or above to console, and if a -v option is set
to ALSO log everything at DEBUG or above to a file.  However, while I
DO get the log file created, and log messages are appearing there,
Debug messages are not...

Here's some sample code that is essentially the guts of the logging
setup right now, based on what I read in the docs:


#!/usr/bin/python

import logging
import sys

verbose = True

# Set up the logger
console_format = '%(levelname)-8s %(message)s'
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter(console_format))
console_handler.setLevel(logging.INFO)
logger = logging.getLogger()
logger.addHandler(console_handler)
if verbose:
    verbose_format = '%(asctime)s %(levelname)-8s %(message)s'
    verbose_handler = logging.FileHandler('testlog.log')
    verbose_handler.setLevel(logging.DEBUG)
    verbose_handler.setFormatter(logging.Formatter(verbose_format))
    logger.addHandler(verbose_handler)
    logging.debug("Setting log level to DEBUG for verbosity")

logging.info("INFO event logged")
logging.warning("WARNING event logged")
logging.error("ERROR event logged")
logging.critical("CRITICAL event logged")
logging.debug("DEBUG event logged")

When I run this I get the following console and log file output:

bladernr at klaatu:~/development/cert-submit-script-improvements/bin$ ./logtest.py
WARNING  WARNING event logged
ERROR    ERROR event logged
CRITICAL CRITICAL event logged
bladernr at klaatu:~/development/cert-submit-script-improvements/bin$ cat
testlog.log
2012-03-06 11:05:40,297 WARNING  WARNING event logged
2012-03-06 11:05:40,297 ERROR    ERROR event logged
2012-03-06 11:05:40,298 CRITICAL CRITICAL event logged

So I AM getting logging, but I am not getting the DEBUG level logs in
the log file, nor am I getting INFO level logs on console.

Any idea what I'm doing wrong?



More information about the Python-list mailing list