0

Python's logging.basicConfig does not behave as I would expect. In the code below messages sent with logging.warn get sent even though I've called basicConfig with a level of ERROR.

import logging

logging.basicConfig(level=logging.ERROR)
root = logging.getLogger()
print("root.level", logging.getLevelName(root.level))
print("Levels for root.handlers: {}".format(
        [logging.getLevelName(handler.level) for handler in root.handlers]))
logging.warn("You're seeing this even though you called basicConfig with level=logging.ERROR")
root.warn("You're seeing this too")

root.setLevel(logging.ERROR)
logging.warn("But you won't see this")

The output produced is

root.level WARNING
Levels for root.handlers: ['NOTSET']
WARNING:root:You're seeing this even though you called basicConfig with level=logging.ERROR
WARNING:root:You're seeing this too

Note that the final call to logging.warn, once I've called root.setLevel myself, does indeed fail to produce output as expected.

What good is the level argument for logging.basicConfig if it has no effect in this simple setting? And if I want to control what level of messages get output in a simple setting such as this one, is the preferred approach to call root.setLevel?

Here's my version info:

# sys.version = 3.4.3 |Continuum Analytics, Inc.| (default, Mar  6 2015, 12:03:53) [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]

There are several questions already on stackoverflow that seem to be the same as this one, but all the ones I've found are actually about other things:

  1. This guy is trying to run logging.basicConfig after he's already done some logging
  2. This question attempts to call logging.basicConfig more than once (producing an effect similar to #1)
  3. This question involves using a child logger
Community
  • 1
  • 1
kuzzooroo
  • 6,788
  • 11
  • 46
  • 84

1 Answers1

1

Using the code as given, I have been unable to replicate your problem. Instead, the output is as expected.

root.level ERROR
Levels for root.handlers: ['NOTSET']

Is it possible that you have a sitecustomize.py or usercustomize.py that is being invoked by python at startup? These are often used to provide logging setups.

The function basicConfig does nothing at all if the root handlers have already been initialised. So, if you have such a file doing setup already, then this second basicConfig call will be a no-op.

Try running your code using either of the following:

python3.4 -I 

or

python2.7 -ES

These flags will help isolate your environment and prevent the import of site (which then imports sitecustomize etc).

donkopotamus
  • 22,114
  • 2
  • 48
  • 60