Python使用简单示例记录问题

时间:2017-02-27 13:20:53

标签: python logging

我尝试了一个基于官方Logging Cookbook的简单示例,但结果出乎意料:

LOG_PATH = 'logs'

logger = logging.getLogger(__name__)

# Creates 2 Handlers to split log levels
info_fh = logging.FileHandler(path.join(LOG_PATH, 'info_level.log'))
info_fh.setLevel(logging.INFO)
err_fh = logging.FileHandler(path.join(LOG_PATH, 'err_level.log'))
err_fh.setLevel(logging.ERROR)

# Create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
info_fh.setFormatter(formatter)
err_fh.setFormatter(formatter)

# add the handlers to logger
logger.addHandler(info_fh)
logger.addHandler(err_fh)

然后我在控制台中写道:

In [2]: logger.info("hello")
In [3]: logger.error("bad")

随后:

cat logs/err_level.log
>>> 2017-02-27 13:16:40,328 - jive - ERROR - bad

cat logs/info_level.log
>>> 2017-02-27 13:16:40,328 - jive - ERROR - bad

我不明白为什么info_level.log文件不包含"你好"记录。

1 个答案:

答案 0 :(得分:3)

这可能意味着您的logger自己的级别高于logging.INFO(20)。该值继承自父记录器:

>>> logger.level  
0  # that means it is not set
>>> logging.NOTSET
0
>>> logger.getEffectiveLevel()
30  # value of parent because not set
>>> logger.parent.level       
30
>>> logging.INFO
20  # < logger.getEffectiveLevel()  -> not picked up

手动设置记录器级别:

>>> logger.setLevel(logging.DEBUG)
>>> logger.getEffectiveLevel()
10

现在将拾取info日志。来自Logger.getEffectiveLevel docs

  

表示此记录器的有效级别。如果使用setLevel()设置了NOTSET以外的值,则返回该值。否则,将遍历层次结构,直到找到NOTSET以外的值,并返回该值

其他地方:

  

请注意,根记录器的创建级别为WARNING。