请考虑以下代码段:
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')
的调用,则会同时显示FLAG1
和FLAG2
,并且我想这是因为生成的线程缺少了dictConfig
创建的某些全局记录器配置。还是有一种方法可以将记录器传递给生成的线程并保持相同的记录行为,而不必通过记录器配置字典吗?