Logging setLevel is being ignored

The below code is copied from the documentation. I am supposed to be able to see all the info logs. But I don’t. I am only able to see the warn and above even though I’ve set setLevel to INFO.

Why is this happening? foo.py:

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

Output:

workingDirectory$ python foo.py
warn message
error message
critical message

Where did the info and debug messages go??

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Replace the line

logger.setLevel(logging.DEBUG)

with

logging.basicConfig(level=logging.DEBUG, format='%(message)s')

and it should work as expected. If you don’t configure logging with any handlers (as in your post – you only configure a level for your logger, but no handlers anywhere), you’ll get an internal handler “of last resort” which is set to output just the message (with no other formatting) at the WARNING level.

Method 2

Try running logging.basicConfig() in there. Of note, I see you mention INFO, but use DEBUG. As written, it should show all five messages. Swap out DEBUG with INFO, and you should see four messages.

import logging

logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

edit: Do you have logging set up elsewhere in your code already? Can’t reproduce the exact behavior you note with the specific code provided.

Method 3

As pointed by some users, using:

logging.basicConfig(level=logging.DEBUG, format='%(message)s')

like written in the accepted answare is not a goot option because it sets the loglevel globally, so it will log debug message from every logger.

In my case the best solution to set log level just for my logger was:

import logging

logger = logging.getLogger('MyLogger')
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)

Not really intuitive solution, but is necessary if you want to set loglevel only for ‘MyLogger’ and not globally.

Method 4

This is technically also an “answer”, because it can “solve” the problem. BUT I definitely DO NOT like it. It is not intuitive, and I lost 2+ hours over it.

Before:

import logging
logger = logging.getLogger('foo')
logger.setLevel(logging.INFO)
logger.info('You can not see me')
# Or you can just use the following one-liner in command line.
# $ python -c "import logging; logger = logging.getLogger('foo'); logger.setLevel(logging.INFO); logger.info('You can not see me')"

After:

import logging

logging.debug('invisible magic')  # <-- magic

logger = logging.getLogger('foo')
logger.setLevel(logging.INFO)
logger.info('But now you can see me')
# Or you can just use the following one-liner in command line.
$ python -c "import logging; logging.debug('invisible magic'); logger = logging.getLogger('foo'); logger.setLevel(logging.INFO); logger.info('But now you see me')"

PS: Comparing it to the current chosen answer, and @Vinay-Sajip’s explanation, I can kind of understand why. But still, I wish it was not working that way.

Method 5

The accepted answer does not work for me on Win10, Python 3.7.2.

My solution:

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

It’s order sensitive.

Method 6

You have to set the basicConfig of the root logger to DEBUG, then you can set the level of your individual loggers to more restrictive levels.

This is not what I expected. Here is what I had to do:

#!/usr/bin/env python3

import logging
# by default this is WARNING.  Leaving it as WARNING here overrides 
# whatever setLevel-ing you do later so it seems they are ignored.
logging.basicConfig(level=logging.DEBUG)

l = logging.getLogger(__name__)
l.setLevel(level=logging.INFO)
# if I hadn't called basicConfig with DEBUG level earlier, 
# info messages would STILL not be shown despite calling 
# setLevel above.  However now debug messages will not be shown 
# for l because setLevel set it to INFO

l.warning('A warning message will be displayed')
l.info('A friendly info message will be displayed')
l.debug('A friendly debug message will not be displayed')

Method 7

If you want this to work WITHOUT basicConfig, you have to first set up the lowest possible level you’ll log onto the logger. Since the logger sets a minimum threshold, handlers which have a lower threshold but belong to the same logger won’t get those lower threshold messages since they’re ignored by the logger in the first place. Intuitive, but not obvious.

We start by doing this:

lgr = logging.getLogger(name)
lgr.setLevel(logging.DEBUG)

Then, set up the handlers with the different levels you need, in my case I want DEBUG logging on stdout and INFO logging to a rotating file, so I do the following:

rot_hndlr = RotatingFileHandler('filename.log',
                                maxBytes=log_size,
                                backupCount=3)
    
rot_hndlr.setFormatter(formatter)
rot_hndlr.setLevel(logging.INFO)
lgr.addHandler(rot_hndlr)

stream_hndlr = logging.StreamHandler()
stream_hndlr.setFormatter(stream_formatter)
lgr.addHandler(stream_hndlr)

Then, to test, I do this:

lgr.debug("Hello")
lgr.info("There")

My stdout (console) will look like this:

Hello
There

and my filename.log file will look like this:

There

Method 8

In short, change the level in logging.basicConfig will influence the global settings.
You should better set level for each logger and the specific handler in the logger.

The following is an example that displays all levels on the console and only records messages >= errors in log_file.log. Notice the level for each handler is different.

import logging
# Define logger
logger = logging.getLogger('test')

# Set level for logger
logger.setLevel(logging.DEBUG)

# Define the handler and formatter for console logging
consoleHandler = logging.StreamHandler() # Define StreamHandler
consoleHandler.setLevel(logging.DEBUG) # Set level
concolsFormatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s') # Define formatter
consoleHandler.setFormatter(concolsFormatter) # Set formatter
logger.addHandler(consoleHandler) # Add handler to logger

# Define the handler and formatter for file logging
log_file = 'log_file'
fileHandler = logging.FileHandler(f'{log_file}.log') # Define FileHandler
fileHandler.setLevel(logging.ERROR) # Set level
fileFormatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # Define formatter
fileHandler.setFormatter(fileFormatter) # Set formatter
logger.addHandler(fileHandler) # Add handler to logger

# Test
logger.debug('This is a debug')
logger.info('This is an info')
logger.warning('This is a warning')
logger.error('This is an error')
logger.critical('This is a critical')

Console output:

# Test
test - DEBUG - This is a debug
test - INFO - This is an info
test - WARNING - This is a warning
test - ERROR - This is an error
test - CRITICAL - This is a critical

File log_file.log content:

2021-09-22 12:50:50,938 - test - ERROR - This is an error
2021-09-22 12:50:50,938 - test - CRITICAL - This is a critical

To review your logger‘s level:

logger.level

The result should be one of the following:

10 # DEBUG
20 # INFO
30 # WARNING
40 # ERROR
50 # CRITICAL

To review your handlers‘s levels:

logger.handlers
[<StreamHandler stderr (DEBUG)>,
 <FileHandler ***/log_file.log (ERROR)>]

Method 9

Most of the answers that I’ve found for this issue uses the basicConfig of the root logger.

It’s not helpful for those who intend to use multiple independent loggers that were not initialised with basicConfig. The use of basicConfig implies that the loglevels of ALL loggers will be changed. It also had the unfortunate side effect of generating duplicate logs.

So I tried over several days experimenting with different ways to manipulate the loglevels and came up with one that finally worked.

The trick was to not only change the log levels of all the handlers but also the all the handlers of the parent of the logger.

    def setLevel(self, infoLevel):
    # To dynamically reset the loglevel, you need to also change the parent levels as well as all handlers!

    self.logger.parent.setLevel(infoLevel)
    for handler in self.logger.parent.handlers:
        handler.setLevel(infoLevel)

    self.logger.setLevel(infoLevel)
    for handler in self.logger.handlers:
        handler.setLevel(infoLevel)

The inspiration came from the fact that the basicConfig changes the root logger settings, so I was trying to do the same without using basicConfig.

For those that are interested, I did a little Python project on Github that illustrates the different issues with setting loglevel of the logger (it works partially), proves the SLogger (Sample Logger) implementation works, and also illustrates the duplicate log issue with basicConfig when using multiple loggers not initialised with it.

https://github.com/FrancisChung/python-logging-playground

TLDR: If you’re only interested in a working sample code for the logger, the implentation is listed below

import logging

CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0


class SLogger():
    """
    SLogger : Sample Logger class using the standard Python logging Library

    Parameters:
        name        : Name of the Logger
        infoLevel   : logging level of the Logger (e.g. logging.DEBUG/INFO/WARNING/ERROR)
    """

    def __init__(self, name: str, infoLevel=logging.INFO):
        try:
            if name is None:
                raise ValueError("Name argument not specified")

            logformat = '%(asctime)s %(levelname)s [%(name)s %(funcName)s] %(message)s'
            self.logformat = logformat
            self.name = name.upper()
            self.logger = logging.getLogger(self.name)
            self.logger.setLevel(infoLevel)

            self.add_consolehandler(infoLevel, logformat)

        except Exception as e:
            if self.logger:
                self.logger.error(str(e))

    def error(self, message):
        self.logger.error(message)

    def info(self, message):
        self.logger.info(message)

    def warning(self, message):
        self.logger.warning(message)

    def debug(self, message):
        self.logger.debug(message)

    def critical(self, message):
        self.logger.critical(message)

    def setLevel(self, infoLevel):
        # To dynamically reset the loglevel, you need to also change the parent levels as well as all handlers!
        self.logger.parent.setLevel(infoLevel)
        for handler in self.logger.parent.handlers:
            handler.setLevel(infoLevel)

        self.logger.setLevel(infoLevel)
        for handler in self.logger.handlers:
            handler.setLevel(infoLevel)

        return self.logger.level

    def add_consolehandler(self, infoLevel=logging.INFO,
                           logformat='%(asctime)s %(levelname)s [%(name)s %(funcName)s] %(message)s'):
        sh = logging.StreamHandler()
        sh.setLevel(infoLevel)

        formatter = logging.Formatter(logformat)
        sh.setFormatter(formatter)
        self.logger.addHandler(sh)


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x