Search code examples
pythonloggingerror-logging

Python logging won't set a logging level using basicConfig


For some reason, logging.basicConfig is ignoring the logger level that I'm giving it. The following code is in a script of mine:

# main.py
print logging.getLogger().getEffectiveLevel()
print logger_level
logging.basicConfig(format=logger_format,
                    level=logger_level,
                    )
print logging.getLogger().getEffectiveLevel()

The output is:

30
10
30

So, it's not actually setting the logger level. However, if I execute this exact code in an interactive interpreter, I get the following output:

30
10
10

Which means I'm setting the logging level just fine. Even more confusing, this is a recent occurrence – I don't know what I did that caused this behaviour. Can anyone provide some insight?

Edit: In case of related questions, I've tried running main.py both from my IDE (Sublime Text) as well as from the command line, both with the same result. I'm working in a conda-based virtual environment, and I've tried running the code both in the environment and not (but only from the interpreter - the script can't handle the general environment) with the same result.


Solution

  • From the python logging module docs,

    This function does nothing if the root logger already has handlers configured for it.

    My assumption is that you called basicConfig() prior, which installs handlers.

    Try setting the loglevel directly on the root logger.

    logging.getLogger().setLevel(logger_level)
    

    If you want to change the formatting, then you'll need to give the handler a new formatter. The following might work, assuming a handler has already been added to the root logger.

    logging.getLogger().handlers[0].setFormatter(logging.Formatter(logger_format))