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.
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))
An issue I (stupidly) had was not putting logging.basicConfig()
at the top of the main file.
From the docs:
The above module-level convenience functions (debug, info, warn, error, fatal), which delegate to the root logger, call basicConfig() to ensure that at least one handler is available.
This function (
basicConfig()
) does nothing if the root logger already has handlers configured, unless the keyword argumentforce
is set to True.
I called a function which logged a message before calling logging.BasicConfig()
in my script, so the logger's level was set to the default, rather than the level I wanted.
If it's not possible to move the logger higher in the file, you have two options:
Python 3.8 and above:
logging.basicConfig(level=logging.INFO, force=True)
Python 2.x and Python 3.x:
logging.getLogger().setLevel(logger_level)
To see basicConfig()
overwriting in action, try this:
import logging
logging.info("Can't see me!")
logging.warn("Peekabo")
logging.basicConfig(level=logging.INFO)
logging.info("Hidden again!")
logging.basicConfig(level=logging.INFO, force=True)
logging.info("You found me!")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With