python 的logging模块的日志级别设置不生效

<coding-1 lang="python">
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)s[line:%(lineno)d][%(levelname)s] %(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')
</coding>

输出:
2017-02-10 18:00:26,408 test.py[line:32][WARNING] This is warning message
2017-02-10 18:00:26,408 test.py[line:33][ERROR] error
2017-02-10 18:00:26,408 test.py[line:34][CRITICAL] critical

设置的日志级别是NOTSET,实际上是WARNING
求解释:

至尊宝
至尊宝
1159
编辑于2019-02-13
评论 (1)链接2017-02-10 
  • 1 支持
    因为你混淆了 handler 的 level 和 logger 的 level。上面你设置的是 handler 的 level,而 logger 的 level 没有设置,默认是 WARNING。 – 至尊宝 2019-02-13

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)s[line:%(lineno)d][%(levelname)s] %(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.getLogger('').setLevel(logging.NOTSET)

logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
logging.error('error')

该答案已被锁定,无法对其进行评论,编辑及投票。
()
评论 (0)链接 • 2017-02-10
德问是一个专业的编程问答社区,请 登录注册 后再提交答案