为什么我的记录器输出不是来自非主模块?

时间:2016-02-23 18:20:55

标签: python logging

我有以下文件结构:

config.yaml
main.py
tools/
 misc_utils.py
 extractor.py

misc_utils.py包含以下函数来检索我的记录器:

import logging
import logging.config

def get_logger(module_name, config=None):
    if config is not None:
        logging.config.dictConfig(config)
    return logging.getLogger(module_name)

main.py中,我称之为该功能:

from tools.misc_utils import get_logger
import tools.extractor
with open('config.yaml') as f:
    config = yaml.load(f)
logger = get_logger(__name__, config=config)
logger.info("this outputs ok")

如果我从extractor.py拨打main.pymain.py中的导入行,则由于某种原因它不会输出任何内容:

from .misc_utils import get_logger

logger = get_logger(__name__, 'config.yaml')
logger.info("this doesn't appear in the log")

最后这里是config.yaml

# Logging
version: 1
formatters:
    default:
        format: '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'
handlers:
    console:
        class: logging.StreamHandler
        stream: ext://sys.stdout
        formatter: default
        level: DEBUG
    file:
        class: logging.FileHandler
        filename: main.log
        formatter: default
        level: DEBUG
root:
    handlers: [console, file]
    level: DEBUG

我的问题是,为什么在extractor.py中没有输出任何内容?

2 个答案:

答案 0 :(得分:0)

使用包含此代码的extractor.py:

import yaml
from .misc_utils import get_logger

with open('config.yaml') as f:
    config = yaml.load(f)

logger = get_logger(__name__, config=config)
logger.info("this doesn't appear in the log")
logger.info("this doesn't appear in the log")

和main.py看起来像这样:

import yaml
from tools.misc_utils import get_logger

from tools import extractor

with open('config.yaml') as f:
    config = yaml.load(f)
logger = get_logger(__name__, config=config)
logger.info("this outputs ok")

它对我有用。这是输出:

$ python3 main.py
2016-02-24 23:10:51,314 tools.extractor INFO     this doesn't appear in the log
2016-02-24 23:10:51,320 __main__     INFO     this outputs ok

或者,如果您只想使用现有的记录器 extractor.py,即:

from .misc_utils import get_logger

logger = get_logger(__name__)
logger.info("this doesn't appear in the log")

然后重要的是记录器在之前被初始化 进口。在main.py中有这个:

import yaml
from tools.misc_utils import get_logger

with open('config.yaml') as f:
    config = yaml.load(f)
logger = get_logger(__name__, config=config)
logger.info("this outputs ok")

from tools import extractor

我明白了:

python3 main.py
2016-02-24 23:59:18,350 __main__     INFO     this outputs ok
2016-02-24 23:59:18,350 tools.extractor INFO     this doesn't appear in the log

答案 1 :(得分:0)

我终于弄明白了问题所在。由于import tools.extractorget_logger(__name__, config=config)之前被称为,因此extractor.py中的记录器被禁用。这在dictConfigdisable_existing_loggers参数说明中提到,默认情况下设置为True。将其设置为False可以解决问题。