我看着它的代码,有些困惑。
Does python logging support multiprocessing?
环境
python 3.6.6
记录0.5.1.2
测试代码
import time
import logging
from multiprocessing import Process, current_process, pool
print(logging.__version__)
# setup log
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='test.log',
filemode='w')
def func(the_time, logger):
proc = current_process()
while True:
if time.time() >= the_time:
logger.info('proc name %s id %s %s' % (proc.name, proc.pid, str(proc.name)*5000))
return
if __name__ == '__main__':
the_time = time.time() + 5
for x in range(1, 10):
proc = Process(target=func, name=x, args=(the_time, logger))
proc.start()
问题
使用Python 3.6.6,多进程无需更改即可写入同一文件 混乱。
如果您使用Python 2.7,则会引起混乱。
如果您知道问题所在,请告诉我。谢谢。
答案 0 :(得分:0)
无论Python版本如何,不同的进程都应该在不同步的情况下进行编写,因此记录会变得混乱。
Python不会自动为您解决此问题,但是它具有帮助的工具。
在Python 3中,使用QueueHandler和QueueListener。
在Python 2或3中,使用仅在Linux上有效的multiprocessing-logging。