【问题标题】:How to create a specific logger for my message?如何为我的消息创建特定的记录器?
【发布时间】:2021-02-06 00:36:11
【问题描述】:

我花了太多时间在这上面,我自己也搞不清楚。

我正在编写一些使用某些模块的代码,所以我想为我的消息创建一个特定的记录器,而不是来自其他模块的记录器(它们太多了,所以我不想为每个模块设置不同的级别其中)。

我已将我的用例简化为:

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')               

当我执行前面的代码时,我希望我的信息消息被记录下来。

相反,我得到了:

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

DEBUG 相同,它总是打印警告/错误/关键消息,而不是调试/信息。

如果我提高日志记录级别(比如说ERROR),它会按预期工作。

python --version
Python 3.9.1

【问题讨论】:

    标签: python logging


    【解决方案1】:

    在包级别/根记录器(documentation)更改配置。

    logging.basicConfig(level=logging.INFO)
    

    【讨论】:

    • 添加这个作品,谢谢。但我还是不明白为什么。根据文档:```` 如果没有为根记录器定义处理程序,函数 debug()、info()、warning()、error() 和 critical() 将自动调用 basicConfig()。 ```
    【解决方案2】:

    使用日志模块记录事件:

    import logging 
      
    #Creating an object 
    logger=logging.getLogger() 
      
    #Setting the threshold of logger to DEBUG 
    logger.setLevel(logging.DEBUG) 
      
    #Test messages 
    logger.debug("Debug Message") 
    logger.info("An information") 
    logger.warning("Warning") 
    logger.error("Error message") 
    logger.critical("critical Message") 
    

    【讨论】:

    • 不起作用,这是我发布的代码。除非调用 logging.basicLogging(),否则永远不会打印调试/信息消息(请参阅 arhr 的响应)。
    猜你喜欢
    • 2020-09-10
    • 1970-01-01
    • 2019-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-26
    • 1970-01-01
    相关资源
    最近更新 更多