1

// , The one line answer to "how do I set my logging level to debug?" is usually something like the following:

logging.basicConfig(level=logging.DEBUG)

However, one may be tempted to change it later, back to something like INFO.

logging.basicConfig(level=logging.INFO)

This does not work, however. logging.basicConfig(level=logging.INFO), if run again at the same scope in the same process, will not result in a change to the level of the messages logged.

The official Python documentation, near the middle of https://docs.python.org/2/howto/logging.html#logging-to-a-file, lists the following:

The call to basicConfig() should come before any calls to debug(), info() etc. As it’s intended as a one-off simple configuration facility, only the first call will actually do anything: subsequent calls are effectively no-ops.

Source: https://docs.python.org/2/howto/logging.html#logging-basic-tutorial

Neither, however, does Logger.setLevel() work for this.

The following code attempts to set a lower log level:

logging.basicConfig(level=logging.DEBUG)
logging.debug("setting logging.basicConfig(level=logging.WARNING)")
logging.debug(myLogger.getEffectiveLevel())
logging.basicConfig(level=logging.WARNING) # This does nothing. 
logging.getLogger('root').setLevel(level=logging.WARNING)
logging.debug(myLogger.getEffectiveLevel())
logging.debug("logger root, currently at " \
            + str(logging.getLogger('root').getEffectiveLevel()) \
            + " is enabled for" \
            + str(logging.getLogger('root').isEnabledFor(logging.DEBUG)))

This results in the following output:

DEBUG:root:setting logging.basicConfig(level=logging.WARNING)
DEBUG:root:10
DEBUG:root:30
DEBUG:root:30is enabled forFalse

It seems like one cannot "set" a Logger to a lower level of verbosity without access to something else created with logging.basicConfig().

How does a Python script change its logging level halfway through execution?

Community
  • 1
  • 1
Nathan Basanese
  • 8,475
  • 10
  • 37
  • 66

1 Answers1

0

logging.disable(logging.INFO) → disable messages at logging.INFO and lower, until...

logging.disable(logging.NOTSET) → resume normal logging

Link: https://docs.python.org/2/library/logging.html#logging.disable

Use this to temporarily throttle logging output.
It temporarily overrides the log levels for all loggers.
If you need to shut down logging, use the creatively named logging.shutdown()

First of all, logging.basicConfig() is a constructor, which creates a StreamHandler object to connect to the root logger.

Logging levels are just integer constants, not magic properties of a Python script.

To actually change the level for that specific logger, root, you may need to access the StreamHandler created for it by logging.basicConfig().

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Nathan Basanese
  • 8,475
  • 10
  • 37
  • 66