Skip to content
Advertisement

How to create a specific logger for my message?

I have spent far too much time on this and I couldn’t figure out by myself.

I am writing some code that use some modules, so I want to create a specific logger for my message, not those from the other modules (they are far too many so I don’t want to set a different level for each of them).

I have simplified my use case to:

import logging                                              
                                                            
logger = logging.getLogger('test')                          
logger.setLevel(level=logging.INFO)                                               
print(logging.Logger.manager.loggerDict)                    
                                                            
logger.debug('This is a debug message')                     
logger.info('This is an info message')                      
logger.warning('This is a warning message')                 
logger.error('This is an error message')                    
logger.critical('This is a critical message')               

When I execute the previous code, I would expect to have my info message logged.

Instead I got:

python3 test.py
{'test': <Logger test (INFO)>}
This is a warning message
This is an error message
This is a critical message

Same with DEBUG, it always print warning/error/critical messages, not the debug/info.

If I raise the logging level (let’s say ERROR), it works as expected.

python --version
Python 3.9.1

Advertisement

Answer

Change the configuration at the package level / root logger (documentation).

logging.basicConfig(level=logging.INFO)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement