如何判断Python中的根日志记录器是否设置为DEBUG级别?
如果我通过命令行参数把日志模块设置为DEBUG,像这样:
if (opt["log"] == "debug"):
logging.basicConfig(level=logging.DEBUG)
那么我怎么知道日志记录器是否被设置为DEBUG呢?我正在写一个装饰器,如果传入了True的标志,它会记录一个函数的执行时间;如果没有传入标志,它默认在根日志记录器设置为DEBUG时打印时间信息。
3 个回答
3
只是
logging.getLogger().level == logging.DEBUG
134
其实,还有一个更好的方法:使用代码 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()
129
logging.getLogger().getEffectiveLevel()
使用logging.getLogger()
而不传任何参数时,会得到一个根级别的日志记录器。
你可以在这里查看详细信息:http://docs.python.org/library/logging.html#logging.Logger.getEffectiveLevel