ProcessPoolExecutor日志记录失败?

2024-10-02 02:36:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个多处理程序来处理多个批处理,但我的日志记录无法将批记录到日志文件中,只能记录根日志信息会被记录,如何设置日志才能正确打印到日志文件中?在

日志只会打印这样一行“信息:根目录:这是根日志记录 ““

import logging
import concurrent.futures
def process_batchs():
    batches = [i for i in range(100)]
    logging.basicConfig(filename=r'doc\test_ProcessPoolExecutor.log', filemode='w+',level=logging.DEBUG)
    logging.info('this is root logging')
    with concurrent.futures.ProcessPoolExecutor(10) as e:
        futures = []
        for batch in batches:
            future = e.submit(f, batch)
            futures.append(future)
        while True:
            dones = [future.done() for future in futures]
            if all(dones):
               results = [future.result() for future in futures]
               print results
               break
def f(batch):
    # do some thing
    logging.info('this is sub logging' + str(batch))
    return batch


if __name__ == '__main__':
    process_batchs()

在windows/python2.7上运行


Tags: 文件inimport信息forloggingdefbatch
1条回答
网友
1楼 · 发布于 2024-10-02 02:36:32

日志记录在每个子进程中使用不同的实例,并且不能写入同一个文件。Apply follow fix可以解决这个问题,但是我认为更好的解决方案可能是使用singleton模式日志记录.getlogger('abc')?在

import logging
import concurrent.futures
def process_batchs():
    batches = [i for i in range(100)]
    logging.basicConfig(filename=r'test_ProcessPoolExecutor.log', filemode='w+',level=logging.DEBUG)
    logging.info('this is root logging')
    with concurrent.futures.ProcessPoolExecutor(10) as e:
        futures = []
        for batch in batches:
            future = e.submit(f, batch)
            futures.append(future)
        while True:
            dones = [future.done() for future in futures]
            if all(dones):
               results = [future.result() for future in futures]
               print results
               break
def f(batch):
    # do some thing
    # Here is the trick, notice here!!!
    ########
    logging.basicConfig(filename=r'test_ProcessPoolExecutor.log', filemode='w+',level=logging.DEBUG)
    ########
    logging.info('this is sub logging' + str(batch))
    return batch


if __name__ == '__main__':
    process_batchs()

相关问题 更多 >

    热门问题