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

gct*_*gct 87 python logging decorator

如果我使用命令行参数将日志记录模块设置为DEBUG:

if (opt["log"] == "debug"):
  logging.basicConfig(level=logging.DEBUG)
Run Code Online (Sandbox Code Playgroud)

我怎样才能告诉记录器是否设置为DEBUG?我正在编写一个装饰器,如果传递了True标志,它将为一个函数计时,如果没有给出标志,它将默认为在根记录器设置为DEBUG时打印定时信息.

Tor*_*amo 106

logging.getLogger().getEffectiveLevel()
Run Code Online (Sandbox Code Playgroud)

logging.getLogger() 没有参数获取根级别记录器.

http://docs.python.org/library/logging.html#logging.Logger.getEffectiveLevel

  • 如果您想要level的名称而不是数字,可以使用它将数字转换为字符串(如'INFO'):logging.getLevelName() (5认同)
  • @ guettli,getLevelName()需要一个参数,该参数包含要获取其文本表示形式的级别。因此调用实际上就是这个野兽:`logging.getLevelName(logging.getLogger()。getEffectiveLevel())`。当您想要的只是当前级别的字符串时,使用更简单的语法会很好。 (2认同)

Pat*_*Pat 96

实际上,还有一个更好:使用代码logging.getLogger().isEnabledFor(logging.DEBUG).我试图理解如何处理结果时发现了它getEffectiveLevel().

以下是日志记录模块本身使用的代码.

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()
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案,因为它具有较低的运行时复杂性. (4认同)