Python: why logging in multiprocessing not working

2019-09-03 05:26发布

After I port my script to Windows from Mac (both python 2.7.*), I find that all the logging not working in subprocess, only the father's logging are write to file. Here is my example code:

# test log among multiple process env
import logging, os
from multiprocessing import Process

def child():
    logging.info('this is child')

if __name__ == '__main__':
    logging.basicConfig(filename=os.path.join(os.getcwd(), 'log.out'),
            level = logging.DEBUG, filemode='w',
            format = '[%(filename)s:%(lineno)d]: %(asctime)s - %(levelname)s: %(message)s')


    p = Process(target = child, args = ())
    p.start()
    p.join()

    logging.info('this is father')

the output only write this is father into log.out, and the child's log missing. How to make logging woking in child process?

1条回答
smile是对你的礼貌
2楼-- · 2019-09-03 06:02

Each child is an independent process, and file handles in the parent may be closed in the child after a fork (assuming POSIX). In any case, logging to the same file from multiple processes is not supported. See the documentation for suggested approaches.

查看更多
登录 后发表回答