2

The following code changes the log level from INFO to DEBUG, and even though logger.getEffectiveLevel() returns DEBUG, the debug message doesn't get logged, as the output shows.

version of python: 3.10.12

---out.log---

log level 1: INFO
log level 2: DEBUG

Code

import logging
import logging.config

def test_change_log_level():
    logger = logging.Logger("my-logger", logging.INFO)
    file_handler = logging.FileHandler(filename="out.log")

    file_handler.setLevel(logging.INFO)
    logger.addHandler(file_handler)

    logger.debug("should not be logged ...")
    logger.info("log level 1: %s", logging.getLevelName(logger.getEffectiveLevel()))

    logger.setLevel(logging.DEBUG)
    file_handler.setLevel(logging.DEBUG)

    logger.info("log level 2: %s", logging.getLevelName(logger.getEffectiveLevel()))
    logger.debug("debug level is effective")


if __name__ == '__main__':

    test_change_log_level()
0

1 Answer 1

1

From the docs:

Loggers should NEVER be instantiated directly, but always through the module-level function logging.getLogger(name).

Secondly, the handler is not relevant to the problem, so here I've replaced it with a root handler.

import logging
logging.basicConfig(format='')

def test_change_log_level():
    logger = logging.getLogger("my-logger")
    logger.setLevel(logging.INFO)

    logger.debug("should not be logged ...")

    logger.setLevel(logging.DEBUG)

    logger.debug("debug level is effective")

if __name__ == '__main__':
    test_change_log_level()

Output:

debug level is effective
Sign up to request clarification or add additional context in comments.

1 Comment

P.S. Check out How to Ask for tips for future questions, like starting with your own research (namely, reading the docs yourself), and making a minimal reproducible example (namely, removing the handler, but also playing around with your code until you localize the problem to, ideally, a single line).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.