python logging默认打印级别_python的logging日志级别设置不生效

博客内容讲述了在Python中使用logging模块时遇到的日志级别设置不生效的问题。通过示例代码展示了设置日志级别为NOTSET但实际输出级别为WARNING的情况。解释了这是因为根logger的默认级别是WARNING,而不是NOTSET。解决方案是明确设置根logger的日志级别为NOTSET,以确保所有级别日志都能被记录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问 题

import logging

from logging.handlers import RotatingFileHandler

log_file = "log/log"

datetime_format = "%Y-%m-%d %H:%M:%S"

per_log_file_max_size = 10240

backup_count = 3

log_format = "%(asctime)s %(filename)sline:%(lineno)d %(message)s"

rotate_file_handler = RotatingFileHandler(log_file, maxBytes=per_log_file_max_size,

backupCount=backup_count)

rotate_file_handler.setLevel(logging.NOTSET)

formatter = logging.Formatter(log_format)

rotate_file_handler.setFormatter(formatter)

logging.getLogger('').addHandler(rotate_file_handler)

logging.debug('This is debug message')

logging.info('This is info message')

logging.warning('This is warning message')

logging.error('error')

输出:

2017-02-10 18:00:26,408 test.pyline:32 This is warning message

2017-02-10 18:00:26,408 test.pyline:33 error

2017-02-10 18:00:26,408 test.pyline:34 critical

设置的日志级别是NOSET,实际上是WARNING

求解释:

解决方案

因为 NOSET 日志级别的效果是这样的:

Logger.setLevel(lvl)

Sets the threshold for this logger to lvl. Logging messages which are less severe than lvl will be ignored. When a logger is created, the level is set to NOTSET (which causes all messages to be processed when the logger is the root logger, or delegation to the parent when the logger is a non-root logger). Note that the root logger is created with level WARNING.

The term ‘delegation to the parent’ means that if a logger has a level of NOTSET, its chain of ancestor loggers is traversed until either an ancestor with a level other than NOTSET is found, or the root is reached.

If an ancestor is found with a level other than NOTSET, then that ancestor’s level is treated as the effective level of the logger where the ancestor search began, and is used to determine how a logging event is handled.

If the root is reached, and it has a level of NOTSET, then all messages will be processed. Otherwise, the root’s level will be used as the effective level.

因为 logging.getLogger('')(root logger)的默认日志级别是 WARNING 不是 NOSET,所以 rotate_file_handler 将使用这个 WARNING 的日志级别。

将 logging.getLogger('') 的日志级别也改为 NOTSET 就可以了:

logger = logging.getLogger('')

logger.setLevel(logging.NOTSET)

logger.addHandler(rotate_file_handler)

$ cat log

2017-02-10 23:04:23,583 test.pyline:20 This is debug message

2017-02-10 23:04:23,584 test.pyline:21 This is info message

2017-02-10 23:04:23,584 test.pyline:22 This is warning message

2017-02-10 23:04:23,584 test.pyline:23 error

参考:

扫一扫关注IT屋

微信公众号搜索 “ IT屋 ” ,选择关注与百万开发者在一起

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值