Reputation: 1792
When i configure the root logger in a config file. the other children loggers don't follow the same configuration.
main.py
import logging
import logging.config
import test
logging.config.fileConfig("logger.ini")
logger = logging.root
logger.critical("main")
test.f()
test.py
import logging
logger = logging.getLogger(__name__)
def f():
print "inside f"
logger.critical("Test")
print logger.parent.name
print logger.parent.handlers
logger.ini
[loggers]
keys=root
[handlers]
keys=console
[formatters]
keys=form
[logger_root]
level=DEBUG
handlers=console
[handler_console]
class=StreamHandler
formatter=form
args=()
[formatter_form]
format=%(levelname)s:%(name)s:%(message)s
when i run the program i don't have i got
CRITICAL:root:main
inside f
root
[<logging.StreamHandler object at 0x00000000021C4908>]
But i don't have the log from the other file. I thought that if children don't have any handlers he will send the log to his parent. any idea why i don't see the log? or how to fix it?
Upvotes: 5
Views: 5618
Reputation: 3663
What happens here is that the logger fetched in test.py
is created before you call logging.config.fileConfig("logger.ini")
in main.py
. Once fileConfig
is called, any pre-existing loggers not specified in the config file are deleted.
There are two ways I can suggest to solve this:
Do not call logging.getLogger
in a module's global scope, but only when you need the logger inside a function / method
Change your code so when calling fileConfig()
, you specify: logging.config.fileConfig("logger.ini", disable_existing_loggers=False)
. This causes any loggers created before the configuration is applied to be maintained and not disabled.
See https://docs.python.org/2/library/logging.config.html#logging.config.fileConfig for details on option #2.
Upvotes: 8