Python 记录器不打印调试消息,尽管它设置正确
Python logger is not printing debug messages, although it is set correctly
我有以下代码,我只是想玩一下 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('Debug with logger: will print') 没有打印。
您还没有将任何处理程序附加到您的记录器。结果,使用了内部"handler of last resort",它只输出WARNING
及以上级别的事件。请参阅文档的 this part 以查看如果未提供处理程序配置会发生什么情况。如果您在 with
语句之前调用 logging.basicConfig()
,则应显示 DEBUG
消息。
请注意,文档还包含 working example 使用上下文管理器进行日志记录的内容。
我有以下代码,我只是想玩一下 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('Debug with logger: will print') 没有打印。
您还没有将任何处理程序附加到您的记录器。结果,使用了内部"handler of last resort",它只输出WARNING
及以上级别的事件。请参阅文档的 this part 以查看如果未提供处理程序配置会发生什么情况。如果您在 with
语句之前调用 logging.basicConfig()
,则应显示 DEBUG
消息。
请注意,文档还包含 working example 使用上下文管理器进行日志记录的内容。