如果logging.config.dictConfig()不影响现有记录器,那么它有什么意义?

时间:2016-06-26 01:35:23

标签: python logging

使用logging.Logger提供的API配置记录器,如b.py中所示配置现有记录器。使用logging.config.dictConfig()配置日志记录不会配置现有记录器,如a.py所示。

*.py个文件

~/bar                                                                                    
▶ tail -n +1 *.py
==> a.py <==
import logging
from logging.config import dictConfig

logger = logging.getLogger(__name__)

logging_config = dict(
    version = 1,
    handlers = {
        'h': {'class': 'logging.StreamHandler'}
    },
    root = {
        'handlers': ['h'],
        'level': logging.DEBUG
    }
)

dictConfig(logging_config)

logger.debug("This is a test")

==> b.py <==
import logging

logger = logging.getLogger(__name__)

logging.getLogger().setLevel(logging.DEBUG)
logging.getLogger().addHandler(logging.StreamHandler())

logger.debug("This is a test")

的I / O

~/bar                                                                                    
▶ python -m a

~/bar                                                                                    
▶ python -m b
This is a test

如果库在logging.config.dictConfig()设置之前创建了记录器,则记录器将无法正确配置。库如何处理这个?他们是否希望将日志记录配置传递给他们?他们只是在导入过程中避免创建记录器吗?

1 个答案:

答案 0 :(得分:1)

logging.config.dictConfig()确实会影响现有记录器的配置。但是,dictConfig()默认情况下会禁用现有记录器,除非根据16.7.2.1. Dictionary Schema Details传递给disable_existing_loggers = False的词典中定义了dictConfig()