简体   繁体   中英

Python logging - config file in multiple modules with root logger

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?

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:

  1. Do not call logging.getLogger in a module's global scope, but only when you need the logger inside a function / method

  2. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM