2
我剛剛發現了Python日誌記錄的不同行爲,具體取決於我是否使用帶有fileconfig的日誌記錄和使用編程配置進行日誌記錄。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()
在我的第二個例子,我在配置日誌與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,)
那麼,爲什麼第二個例子使用logging fileconfig NOT打印我的調試日誌消息到控制檯?