In Python 2.4 and later, configuring the logging module to have a more basic formatting is easy:
logging.basicConfig(level=opts.LOGLEVEL, format="%(message)s")
but for applications which need to support Python 2.3 it seems more difficult, because the logging API was overhauled in Py2.4. In particular, basicConfig doesn't take any arguments. Trying a variation on the sole example 开发者_StackOverflow社区in the Py2.3 documentation, I get this:
try:
logging.basicConfig(level=opts.LOGLEVEL, format="%(message)s")
except:
logging.getLogger().setLevel(opts.LOGLEVEL)
h = logging.StreamHandler()
h.setFormatter(logging.Formatter("%(message)s"))
logging.getLogger().addHandler(h)
but calling this root logger in Py2.3, e.g.
logging.info("Foo")
gives duplicated output:
Foo
INFO:root:Foo
I can't find a way to modify the format of the existing handler on the root logger in Py2.3 (the "except" block above), hence the "addHandler" call that's producing the duplicated output. Is there a way to set the format of the root logger without this duplication? Thanks!
except:
without exception class[es] is a good way to get in trouble. I believe logging
module in Python 2.3 has basicConfig()
function, but with less options. Since it accepts **kwargs
it may fail at any moment after doing some job. I think it already installed a handler with default format then failed to configure something. After catching exception you have installed another handler. Having 2 handlers you get 2 messages for each event. The simplest way in your case: avoid using basicConfig()
at all and configure logging
manually. And never use except:
if you don't reraise or log caught exception.
精彩评论