set_start_method('spawn')重置记录器配置

时间:2019-04-25 08:42:59

标签: python python-multiprocessing python-logging

请考虑以下代码段:

import logging
import logging.config
from multiprocessing import Process, set_start_method

try:
    set_start_method('spawn')
except RuntimeError:
    pass


def log(logger):
    for _ in range(10):
        logger.info('FLAG2')


if __name__ == '__main__':
    config = {
        "version": 1,
        "formatters": {
            "timestamp": {
                "format": "%(asctime)s: %(message)s"
            },
        },
        "handlers": {
            "stdout": {
                "level": "INFO",
                "formatter": "timestamp",
                "class": "logging.StreamHandler",
                "stream": "ext://sys.stdout"
            },
        },
        "loggers": {
            "some_logger": {
                "level": "INFO",
                "handlers": ["stdout"]
            }
         }
    }

    logging.config.dictConfig(config)

    logger = logging.getLogger("some_logger")

    for _ in range(10):
        logger.info('FLAG1')

    p = Process(target=log, args=(logger,))

    p.start()

    p.join()

这将打印FLAG1十次,包括时间戳,FLAG2不会被写入标准输出。如果我删除对set_start_method('spawn')的调用,则会同时显示FLAG1FLAG2,并且我想这是因为生成的线程缺少了dictConfig创建的某些全局记录器配置。还是有一种方法可以将记录器传递给生成的线程并保持相同的记录行为,而不必通过记录器配置字典吗?

0 个答案:

没有答案