Python记录器不尊重setLevel吗? [英] Python logger not respecting setLevel?

查看:85
本文介绍了Python记录器不尊重setLevel吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了一些时间浏览网站的Python记录器问题,希望在那里解决.我设置了一个带有两个流处理程序的记录器,它们具有不同的格式和级别的记录,这是我的代码库中的一个功能性片段:

I've spent a bit of time looking through the site at Python logger questions hoping my would be resolved there. I've set up a logger with two stream handlers that have both different formats and levels of logging, here's a functional snippet from my codebase:

import os
import time
import logging

LOG_LEVELS = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
TEST_RESULT_LEVELV_NUM = 51

# http://stackoverflow.com/a/11784984/196832
def status(self, message, *args, **kws):
    self._log(TEST_RESULT_LEVELV_NUM, message, args, **kws)

logging.addLevelName(TEST_RESULT_LEVELV_NUM, "RESULT")
logging.Logger.result = status


def setup_logging(level=0, quiet=False, logdir=None):
    logger = logging.getLogger('juju-test')
    ffmt = logging.Formatter('%(asctime)s %(name)s %(levelname)-8s: %(message)s')
    cfmt = logging.Formatter('%(name)s %(levelname)s: %(message)s')
    #logger.setLevel(0)

    if level >= len(LOG_LEVELS):
        level = len(LOG_LEVELS) - 1

    if logdir:
        if not os.path.exists(logdir):
            os.makedirs(logdir)
        logfile = os.path.join(logdir, 'juju-test.%s.log' % int(time.time()))
        fh = logging.FileHandler(logfile)
        # Always at least log to INFO for file, unless DEBUG is requested
        fh.setLevel(LOG_LEVELS[level if level >= 2 else 2])
        fh.setFormatter(ffmt)
        logger.addHandler(fh)

    if not quiet:
        ch = logging.StreamHandler()
        ch.setLevel(LOG_LEVELS[level])
        ch.setFormatter(cfmt)
        logger.addHandler(ch)

    return logger

我一直在使用 argparse 来提供它,但出于测试目的,如果您提供以下功能:

I've been using an argparse to feed this, but for testing purposes if you feed the following to function:

logger = setup_logging(level=1, logdir="/tmp/oofrab/")
logger.info('Informative!')
logger.warn('Whoa buddy!')
logger.error('Look what you did.')
logger.result("They told me not to make a custom logging level, I'll show them!")
logger.debug('Lots of bugs, man')

我希望在控制台中看到状态错误 warn .然后在日志中statuserrorwarninfo.但是,尽管选择了 logging.INFO ( LOG_LEVELS 列表中的键2),但在控制台和日志文件中我都只能看到 warn .文件处理程序.这是预期的吗?

I'd expect to see status, error, and warn in the console. Then status, error, warn and info in the log. However, I only see down to warn in both console and log file, despite selecting logging.INFO (key 2 in the LOG_LEVELS list) for the file handler. Is this expected?

构建记录器时,我没有使用 basicConfig 或其他任何东西,为什么我不能拥有这两个自定义级别?

I'm not using basicConfig or anything else when building the logger, why can't I have these two custom levels?

推荐答案

显然, logging.NOTSET 并不表示所有级别",而是默认值.因此,将父记录器设置为0级只会将其恢复为默认的接受级别.话虽这么说,如果我将logger.setLevel设置为 logging.DEBUG ,这实际上将日志记录设置为接受所有级别,然后将过滤传递给各种处理程序以进一步过滤.

Apparently, logging.NOTSET does not mean "All levels", but rather defaults. So setting the parent logger to level 0 does only reverts it to it's default accepted levels. That being said, if I set logger.setLevel to logging.DEBUG that essentially sets logging to accept ALL levels then passes filtering on to the various handlers to filter further.

要解决此问题(以及潜在的自定义日志级别),我已将初始记录器级别设置为1

To get around this (and potential custom log levels) I've set the initial logger level to 1

这篇关于Python记录器不尊重setLevel吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆