Python日志记录:使用fileconfig和编程配置之间的不同行为

Ing*_*her 2 python logging

我刚刚发现了Python日志记录的不同行为,具体取决于我是否使用fileconfig进行日志记录并使用程序化配置进行日志记录.

为了演示,我创建了两个最小的例子.

在第一个示例中,我以编程方式配置日志记录.此示例按预期工作 - 将调试日志消息打印到控制台.

# foo.py
import logging

logger = logging.getLogger(__name__)

class Foo(object):
    def __init__(self):
        logger.debug('debug log from Foo')

##########################################################################
# loggingtest.py
import logging.config

from foo import Foo

if __name__ == '__main__':
    consoleLogger = logging.StreamHandler()
    formatter = logging.Formatter(
        '%(asctime)-6s: %(name)s - %(levelname)s - %(message)s')
    consoleLogger = logging.StreamHandler()
    consoleLogger.setLevel(logging.DEBUG)
    consoleLogger.setFormatter(formatter)

    rootLogger = logging.getLogger() 
    rootLogger.addHandler(consoleLogger)
    rootLogger.setLevel(logging.NOTSET)
    # prints debug log message to console
    foo = Foo()
Run Code Online (Sandbox Code Playgroud)

在我的第二个例子中,我正在使用fileConfig配置日志记录.据我所知,log-config-file应该具有完全相同的行为.但是,在此示例中仍未打印调试日志消息.

# foo.py (same as above)
import logging

logger = logging.getLogger(__name__)

class Foo(object):
    def __init__(self):
        logger.debug('debug log from Foo')
##########################################################################
# loggingtest.py
import logging.config

from foo import Foo

if __name__ == '__main__':
    logging.config.fileConfig('logging.cfg')    

    # does NOT print debug log message to console. WHY???
    foo = Foo()

##########################################################################
# logging.cfg
[loggers]
keys = root

[logger_root]
level = NOTSET
handlers = consoleHandler

[formatters]
keys = complex

[formatter_complex]
format = %(asctime)s - %(name)s - %(levelname)s - %(module)s : %(lineno)d - %(message)s

[handlers]
keys = consoleHandler

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=complex
args=(sys.stdout,)
Run Code Online (Sandbox Code Playgroud)

那么为什么使用日志文件配置的第二个示例不将我的调试日志消息打印到控制台?

unu*_*tbu 6

由于fileConfig默认情况下禁用现有记录器,因此请调用

logging.config.fileConfig("logging.cfg")
Run Code Online (Sandbox Code Playgroud)

之前

from foo import Foo
Run Code Online (Sandbox Code Playgroud)

或者打电话

logging.config.fileConfig("logging.cfg",disable_existing_loggers=0)
Run Code Online (Sandbox Code Playgroud)