Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

python - 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
question from:https://stackoverflow.com/questions/66066806/how-to-create-a-specific-logger-for-my-message

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

logging.basicConfig(level=logging.INFO)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...