我正在使用Python 3 multiprocessing.pool和apply_async。
在每个进程中,我都会获得一个记录器,并且每次都会记录到另一个文件。但我看到的是日志文件包含所有进程的所有日志条目。
是否可以让每个进程仅记录进程中记录的条目?
这是一个重现问题的示例代码:
from multiprocessing import Pool
from multiprocessing.pool import ApplyResult
def test(index):
import logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
filename = '{}.log'.format(str(index))
file_handler = logging.FileHandler(filename)
file_handler.setLevel(logging.DEBUG)
logger.addHandler(file_handler)
logger.debug(str(index))
return
if __name__ == '__main__':
results = []
pool = Pool(processes=1)
for i in range(10):
apply_async = pool.apply_async(test, args=(i,))
results.append(apply_async)
map(ApplyResult.wait, results)
pool.close()
pool.join()
生成的第一个日志是 0.log :
0
1
2
3
4
5
6
7
8
9
1.登录:
1
2
3
4
5
6
7
8
9
等
答案 0 :(得分:0)
您是否尝试过在getLogger方法中添加特定名称?
logger = logging.getLogger(str(index))
否则,日志记录模块将默认为root logger。这可以解释为什么每个n个进程都捕获n到9。