Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set logging levels

Tags:

python

logging

I'm trying to use the standard library to debug my code:

This works fine:

import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) logger.info('message') 

I can't make work the logger for the lower levels:

logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) logger.info('message')  logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) logger.debug('message') 

I don't get any response for neither of those.

like image 202
Luis Ramon Ramirez Rodriguez Avatar asked Jul 23 '16 03:07

Luis Ramon Ramirez Rodriguez


People also ask

How do I change the logging level in Java?

Java Util Logging - Log Levels To change a log level we must use Logger#setLevel() and Handler#setLevel() .

How do you create a logging level in Python?

The logging level is set with setLevel . It sets the threshold for this logger to lvl . Logging messages which are less severe than lvl will be ignored. In the example, we change the logging level to DEBUG .


1 Answers

What Python version? That works for me in 3.4. But note that basicConfig() won't affect the root handler if it's already setup:

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

To set the level on root explicitly do logging.getLogger().setLevel(logging.DEBUG). But ensure you've called basicConfig() before hand so the root logger initially has some setup. I.e.:

import logging logging.basicConfig() logging.getLogger().setLevel(logging.DEBUG) logging.getLogger('foo').debug('bah') logging.getLogger().setLevel(logging.INFO) logging.getLogger('foo').debug('bah') 

Also note that "Loggers" and their "Handlers" both have distinct independent log levels. So if you've previously explicitly loaded some complex logger config in you Python script, and that has messed with the root logger's handler(s), then this can have an effect, and just changing the loggers log level with logging.getLogger().setLevel(..) may not work. This is because the attached handler may have a log level set independently. This is unlikely to be the case and not something you'd normally have to worry about.

like image 165
spinkus Avatar answered Sep 28 '22 08:09

spinkus