Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 587
gct Avatar asked Dec 31 '09 23:12

gct


People also ask

What is Python debug logger?

Debugging is an important step of any software development project. The logging module is part of the standard Python library, provides tracking for events that occur while software runs, and can output these events to a separate log file to allow you to keep track of what occurs while your code runs.

What is the default logging level in Python?

The default level is WARNING , which means that only events of this level and above will be tracked, unless the logging package is configured to do otherwise. Events that are tracked can be handled in different ways. The simplest way of handling tracked events is to print them to the console.


Video Answer


1 Answers

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() 
like image 82
Pat Avatar answered Sep 21 '22 07:09

Pat