python多进程log日志问题_使用日志记录多进程/多线程python脚本的死锁

I am facing the problem with collecting logs from the following script.

Once I set up the SLEEP_TIME to too "small" value, the LoggingThread

threads somehow block the logging module. The script freeze on logging request

in the action function. If the SLEEP_TIME is about 0.1 the script collect

all log messages as I expect.

I tried to follow this answer but it does not solve my problem.

import multiprocessing

import threading

import logging

import time

SLEEP_TIME = 0.000001

logger = logging.getLogger()

ch = logging.StreamHandler()

ch.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(funcName)s(): %(message)s'))

ch.setLevel(logging.DEBUG)

logger.setLevel(logging.DEBUG)

logger.addHandler(ch)

class LoggingThread(threading.Thread):

def __init__(self):

threading.Thread.__init__(self)

def run(self):

while True:

logger.debug('LoggingThread: {}'.format(self))

time.sleep(SLEEP_TIME)

def action(i):

logger.debug('action: {}'.format(i))

def do_parallel_job():

processes = multiprocessing.cpu_count()

pool = multiprocessing.Pool(processes=processes)

for i in range(20):

pool.apply_async(action, args=(i,))

pool.close()

pool.join()

if __name__ == '__main__':

logger.debug('START')

#

# multithread part

#

for _ in range(10):

lt = LoggingThread()

lt.setDaemon(True)

lt.start()

#

# multiprocess part

#

do_parallel_job()

logger.debug('FINISH')

How to use logging module in multiprocess and multithread scripts?

解决方案

This is probably bug 6721.

The problem is common in any situation where you have locks, threads and forks. If thread 1 had a lock while thread 2 calls fork, in the forked process, there will only be thread 2 and the lock will be held forever. In your case, that is logging.StreamHandler.lock.

A fix can be found here for the logging module. Note that you need to take care of any other locks, too.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值