Determining if root logger is set to DEBUG level in Python?

PythonLoggingDecorator

Python Problem Overview


If I set the logging module to DEBUG with a command line parameter like this:

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

How can I later tell if the logger was set to DEBUG? I'm writing a decorator that will time a function if True flag is passed to it, and if no flag is given, it defaults to printing timing information when the root logger is set to DEBUG.

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

logging.getLogger().getEffectiveLevel()

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

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

Solution 3 - Python

Just

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongctView Question on Stackoverflow
Solution 1 - PythonPatView Answer on Stackoverflow
Solution 2 - PythonTor ValamoView Answer on Stackoverflow
Solution 3 - PythonKeelungView Answer on Stackoverflow