难以理解Python的记录器传播

时间:2015-09-02 12:52:48

标签: python logging

在定义记录器配置的logging.json文件中,我定义了一个记录器script_logger,其处理程序console设置为将每个记录消息输出到stdout。它有"propagate": "no"因为我不希望将事件传播到根记录器,但是当我创建一个记录消息时,它在stdout上显示两次。

两次没有消息的唯一方法是从console记录器中删除处理程序rootpropagate属性似乎没有效果。

为什么呢?有人可以帮忙吗?

$ python test_script.py
2015-09-02 14:26:35,436 - script_logger - DEBUG - debug msg
2015-09-02 14:26:35,436 - script_logger - DEBUG - debug msg

test_script.py

import logging

if __name__ == "__main__":

    logger = logging.getLogger("script_logger")
    logger.debug("debug msg")

logging.json

{
    "version": 1,
    "disable_existing_loggers": false,
    "formatters": {
        "simple": {
            "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
        }
    },

    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "level": "DEBUG",
            "formatter": "simple",
            "stream": "ext://sys.stdout"
        }, 

        "info_file_handler": {
            "class": "logging.handlers.RotatingFileHandler",
            "level": "INFO",
            "formatter": "simple",
            "filename": "info.log",
            "maxBytes": 10485760,                                                                      
            "backupCount": 20,
            "encoding": "utf8"
        },

        "error_file_handler": {
            "class": "logging.handlers.RotatingFileHandler",                                           
            "level": "ERROR",                                                                          
            "formatter": "simple",
            "filename": "errors.log",                                                                  
            "maxBytes": 10485760,                                                                      
            "backupCount": 20,
            "encoding": "utf8"                                                                         
        }                                                                                              
    },                                                                                                 

    "loggers": {
        "script_logger": {
            "level": "DEBUG",                                                                          
            "handlers": ["console"],                                                                   
            "propagate": "no"
        }
    },                                                                                                 

    "root": {
        "level": "DEBUG",
        "handlers": ["console", "info_file_handler", "error_file_handler"]                             
    }       
} 

1 个答案:

答案 0 :(得分:3)

消息被记录两次,因为console记录器位于rootscript_logger中 - 但我认为您已经知道了。

只需将"propagate": "no"替换为"propagate": False,一切都会按预期工作。