Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why changing the log level dynamically in python does not work

Tags:

python

logging

Changing the log level dynamically does not work.

import logging

logger = logging.Logger("MyLogger", level=logging.INFO)
formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
console = logging.StreamHandler()
console.setFormatter(formatter)
logger.addHandler(console)

logger.setLevel("INFO")
logger.info("should show up")
logger.setLevel(logging.CRITICAL)
logger.info("should not show up")

Output

MyLogger - INFO - should show up
MyLogger - INFO - should not show up

Any suggestion what am I doing wrong?

like image 462
Nabil Ghanem Avatar asked Dec 22 '25 18:12

Nabil Ghanem


1 Answers

It doesn't work in your case because the logger is not being created in the documented way:

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

Creating the logger with logging.Logger(...) has bypassed the logging module's global state, and defeated the hierarchy of the logging tree. Specifically, it has caused an incorrectly cached result to be returned by logger.isEnabledFor().

import logging

# logger = logging.Logger("MyLogger", level=logging.INFO)  # no
logger = logging.getLogger("MyLogger")  # yes

formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
console = logging.StreamHandler()
console.setFormatter(formatter)
logger.addHandler(console)

logger.setLevel("INFO")
logger.info("should show up")
logger.setLevel(logging.CRITICAL)
logger.info("should not show up")

By the way

Elias's answer is "working", but doesn't really tell the whole story here. The answer's claim that you need to change on the logger and its handlers is incorrect.

In fact, there are two setLevel methods (on loggers and handlers). The level set in the logger determines which severity of messages it will pass to its handlers. The level set in each handler determines which messages that handler will send on. In normal usage, setting just one of them up to CRITICAL would have been enough to filter that INFO event.

If you create in the usual way, setting the level on a logger instance will work without fiddling handlers.

like image 174
wim Avatar answered Dec 24 '25 07:12

wim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!