8

每次我认为我理解了日志记录模块时,gremlins 就会进来并改变它的工作方式。(好吧,我承认,那个 gremlin 可能是我在更改我的代码。)

我在这里做错了什么?

> ipython
> import logging
> log = logging.Logger("base")
> log.addHandler(logging.StreamHandler())

> log.critical("Hi")
Hi

> log2 = log.getChild("ment")

> log2.critical("hi")
No handlers could be found for logger "base.ment"

我可以发誓过去,我可以在没有额外配置的情况下使用子记录器......

4

2 回答 2

8

如果你改变

log = logging.Logger('base')

log = logging.getLogger('base')

然后它工作:

import logging

log = logging.getLogger('base')
log.addHandler(logging.StreamHandler())
log.critical('Hi')
log2 = log.getChild('ment')
log2.critical('hi')

产量

Hi
hi
于 2012-07-27T21:56:50.977 回答
3

More detail: You are using the module wrong. :) From looking at the module code, it looks like they don't expect you to ever create a logging.Logger() directly. Many of the functions available directly on the module (ex getLogger()) and the methods on logging.Logger() (ex getChild()) actually proxy through an instance of logging.Manager that the module creates on import. When you create a Logger with logging.Logger() directly, you are actually creating a Logger instance outside of the Manager. When you subsequently call log.getChild(), the module is actually creating the new logger inside the Manager, but with the name of the Manager-external logger appended to the front of the logger name. So your handler added to log is not in the Manager with the spawned child, and thus the handler doesn't work. I am a little confused still though on why adding a handler to log before or after creating log2 causes logging against log2 to behave differently. I don't see what's causing that...

于 2012-07-27T22:29:22.297 回答