NotAName
NotAName

Reputation: 4347

Logging - changing level from INFO to DEBUG disables all logging messages

I have only recently started using Python logging module. I've read docs and some guides, but still am confused as to why logging levels work the way they do.

I have a logger defined in the beginning of the script:

import logging

log_file = f'test.log'
logger = logging.getLogger(__name__)
f_handler = logging.FileHandler(log_file)
f_handler.setLevel(logging.INFO)
f_format = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(message)s',
                             datefmt='%d/%m/%Y %H:%M:%S')
f_handler.setFormatter(f_format)
logger.addHandler(f_handler)
logger.info('Initialising.')

Then throughout the code I have multiple calls to this logger - some info, some exceptions and warnings as well.

Yet, for some reason with the current setup I only get one warning message, if any, although I though that I should be getting all messages above and including INFO level.

To try and test it I switched the logger to DEBUG but I got an empty log as a result.

At the very least I expect to see the following info messages in the log:

self.logger.info('Initialising.') #Right in the __init__ of the class
self.logger.info(f'Using {self.export_file} for export data.') #This one should always be printing unless script fails at the very start
self.logger.info(f'Using {self.model_file} model to predict values.') #Same with this one
self.logger.info('Encoding into a model completed successfully.') #This one as well if script completes successfully, which it normally does

I must be doing something wrong, but I'm not sure what exactly.

Upvotes: 0

Views: 62

Answers (1)

Alexander Dmitriev
Alexander Dmitriev

Reputation: 2525

from setLevel:

When a logger is created, the level is set to NOTSET (which causes all messages to be processed when the logger is the root logger, or delegation to the parent when the logger is a non-root logger). Note that the root logger is created with level WARNING.

Also take a look at logging flow scheme here.

You should call self.logger.setLevel(logging.INFO) to adjust root logger level.

Upvotes: 2

Related Questions