Python setLevel on StreamHandler not working

I have registration settings as follows:

def setUp(): LOG_FORMAT = '%(asctime)s %(levelname)-8s %(name)s %(message)s' #LOG_FORMAT = '%(asctime)s %(name)s %(message)s' logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT) formatter = logging.Formatter(LOG_FORMAT) ch = logging.StreamHandler() ch.setLevel(logging.ERROR) ch.setFormatter(formatter) logging.getLogger().addHandler(ch) LOG_FILENAME = 'file.log' fh = logging.FileHandler(LOG_FILENAME, 'w') fh.setLevel(logging.DEBUG) fh.setFormatter(formatter) logging.getLogger().addHandler(fh) 

However, the console still displays DEBUG messages. Did I miss something?

Please note that setting the ERROR level to fh works fine.

+4
source share
2 answers

I think you need to remove the logging.basicConfig call. This function adds another logging.StreamHandler , which is probably the one that prints messages you don't want to print.

To check this, you can look at the handlers attribute for the root logger (this is a list with all the handlers used) and check the number of logging.StreamHandlers . In addition, it is likely that a message with a level set to logging.ERROR is printed twice due to two logging.StreamHandler s.

My last tip is avoiding using logging.basicConfig if you are going to explicitly configure handlers in your code.

Edit: for completeness only, the source code for logging.basicConfig as follows:

 if len(root.handlers) == 0: filename = kwargs.get("filename") if filename: mode = kwargs.get("filemode", 'a') hdlr = FileHandler(filename, mode) else: stream = kwargs.get("stream") hdlr = StreamHandler(stream) fs = kwargs.get("format", BASIC_FORMAT) dfs = kwargs.get("datefmt", None) fmt = Formatter(fs, dfs) hdlr.setFormatter(fmt) root.addHandler(hdlr) level = kwargs.get("level") if level is not None: root.setLevel(level) 

where you can see that if filename not passed, logging.StreamHandler is created.

+2
source

From Python docs logging.basicConfig :

Does it use the basic configuration for the registration system, creating a StreamHandler with a standard Formatter and adding it to the root of the registrar.

When you set the logging.DEBUG level of the root logger to logging.DEBUG , and you have not disabled message forwarding to the root logger, your DEBUG messages are logged by this StreamHandler created by basicConfig

+2
source

Source: https://habr.com/ru/post/1390307/


All Articles