Python记录器没有打印调试消息,尽管它已正确设置

时间:2017-06-01 16:39:54

标签: python python-3.x logging contextmanager

我有以下代码,我只想玩 logging 模块使用 contextmanager

from contextlib import contextmanager
import logging

@contextmanager
def log_level(level, name):
    logger = logging.getLogger(name)
    old_level = logger.getEffectiveLevel()
    print('log_level.old_level: ' + str(old_level))
    logger.setLevel(level)
    print('log_level.new_level: ' + str(logger.getEffectiveLevel()))
    try:
        yield logger
    finally:
        logger.setLevel(old_level)

if __name__ == '__main__':

    with log_level(logging.DEBUG, 'my-log') as logger:
        print('__main__.log_level.logger.level: ' + str(logger.getEffectiveLevel()))
        logger.debug('Debug with logger: will print')
        logger.warning('Warning')
        print('__main__.log_level.logger.level: ' + str(logger.getEffectiveLevel()))
    print('__main__.logger.level: ' + str(logger.getEffectiveLevel()))

可以看出,在main.log_level中,记录器级别应该是DEBUG,它应该打印消息'Debug with logger:will print'。但是,当我运行代码时,此调试消息不会打印。查看代码的打印件,它表示记录器在log_level内部具有DEBUG级别,并且当它退出log_level时级别返回到WARNING。这是我的输出,当使用python 3执行时:

log_level.old_level: 30
log_level.new_level: 10
__main__.log_level.logger.level: 10
Warning
__main__.log_level.logger.level: 10
__main__.logger.level: 30

我想帮助理解为什么 logger.debug('使用logger调试:将打印')不打印。

1 个答案:

答案 0 :(得分:10)

您尚未将任何处理程序附加到记录器。因此,使用内部“最后手段处理程序”,它仅输出级别WARNING及更高级别的事件。请参阅文档的this part以了解如果未提供处理程序配置会发生什么。如果您在logging.basicConfig()声明之前致电with,则应显示DEBUG条消息。

请注意,文档还包含working example使用带有日志记录的上下文管理器。