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

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

if (opt["log"] == "debug"):
logging.basicConfig(level=logging.DEBUG)

我以后怎样才能知道日志记录器是否被设置为 DEBUG? 我正在编写一个装饰器吗 如果将 True 标志传递给函数,那么它将为函数计时,如果没有给出标志,则默认为 在根日志记录器设置为 DEBUG 时打印计时信息。

54389 次浏览
logging.getLogger().getEffectiveLevel()

logging.getLogger() without arguments gets the root level logger.

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

Actually, there's one better: use the code logging.getLogger().isEnabledFor(logging.DEBUG). I found it while trying to understand what to do with the result of getEffectiveLevel().

Below is the code that the logging module itself uses.

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()

Just

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