为什么Python记录器无法在logging.INFO级别显示信息或调试消息?

时间:2018-06-26 21:31:13

标签: python logging

有人可以向我解释为什么.info()和.debug()调用即使看起来好像也不显示任何内容?我觉得即使经过了日志记录模块文档,我还是有些不了解的东西。

$  python                                    
Python 3.6.5 (default, Apr 25 2018, 14:23:58) 
[GCC 4.2.1 Compatible Apple LLVM 9.1.0 (clang-902.0.39.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import logging
>>> logger = logging.getLogger()
>>> logger.setLevel(logging.INFO)
>>> logger.warning('This is a warning. We should see it.')
This is a warning. We should see it.
>>> logger.debug('This is a debug message. We should not see it.')
>>> logger.info('This is an info message. We should... see it, right?')
>>> logger.setLevel(logging.DEBUG)
>>> logger.info('This is an info message. We should... see it, right?')
>>> logger.debug('Weird. So I guess we are not going to see this as well?')
>>> 

1 个答案:

答案 0 :(得分:4)

它正在记录日志,只是不记录到终端。如果要查看输出到终端的日志(类似于print),则需要添加一个处理程序:

logger.addHandler(logging.StreamHandler())

这样做之后,日志应该按预期显示在您的终端上。