Reputation: 16097
Every time I think I understand the logging module, gremlins come in and change the way it works. (Ok, I'll admit, that gremlin may be me changing my code.)
What am I doing wrong here?
> 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"
I could have sworn that in the past, I was able to use child loggers without additional configuration...
Upvotes: 13
Views: 15675
Reputation: 26150
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...
Upvotes: 3
Reputation: 879331
If you change
log = logging.Logger('base')
to
log = logging.getLogger('base')
then it works:
import logging
log = logging.getLogger('base')
log.addHandler(logging.StreamHandler())
log.critical('Hi')
log2 = log.getChild('ment')
log2.critical('hi')
yields
Hi
hi
Upvotes: 13