如何在Python中确定根记录器是否设置为DEBUG级别?

106
如果我使用类似以下命令行参数将日志模块设置为DEBUG:
if (opt["log"] == "debug"):
  logging.basicConfig(level=logging.DEBUG)

我如何后来知道记录器是否已设置为DEBUG? 我正在编写一个装饰器,如果传递了True标志,则会计时函数, 如果未传递任何标志,则默认在根记录器设置为DEBUG时打印时间信息。


最终,您可能希望使用某些特定内容,而不是将其与记录器耦合,例如opt["time_functions"](您可以根据其他选项默认为True / False)。 - Roger Pate
3个回答

133

实际上,还有一个更好的方法:使用代码logging.getLogger().isEnabledFor(logging.DEBUG)。我是在尝试理解getEffectiveLevel()的结果时发现了它。

下面是logging模块本身使用的代码。

def getEffectiveLevel(self):
    """
    Get the effective level for this logger.

    Loop through this logger and its parents in the blogger hierarchy,
    looking for a non-zero logging level. Return the first one found. 
    """
    logger = self
    while logger:
        if logger.level:
            return logger.level
        logger = logger.parent
    return NOTSET

def isEnabledFor(self, level):
    """
    Is this logger enabled for level ‘level’?
    """
    if self.manager.disable >= level:
        return 0
    return level >= self.getEffectiveLevel()

4
应该接受这个答案,因为它以更低的运行时间复杂度完成了同样的任务。 - AndyJost

129

太好了,谢谢!我正在做类似的事情(除了将显式“root”传递给getLogger之外),但我是在我的装饰器的__init__函数中执行的,在记录器设置为debug之前:\ - gct
5
如果你想要级别的名称而不是数字,可以使用下面这段代码将数字转换为字符串(例如“INFO”):logging.getLevelName() - guettli
2
@guettli,getLevelName()需要一个包含您想要获取其文本表示的级别的参数。因此,调用实际上是这个怪兽:logging.getLevelName(logging.getLogger().getEffectiveLevel())。当您只想获取当前级别的字符串时,拥有更简单的语法会很好。 - Trutane
将整数级别转换为名称:https://docs.python.org/3/library/logging.html#levels - EddyTheB

3

仅仅

logging.getLogger().level == logging.DEBUG

2
这是一个糟糕的答案;它只能检查一个_确切_的级别,而不是像其他地方的评论一样_有效_。isEnabledFor()存在的原因就是为了解决这个问题! - Aaron D. Marasco

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接