Python日志模块在多处理上下文中的混乱行为
因此,我尝试在Python日志模块在多处理上下文中的混乱行为,python,python-2.7,logging,multiprocessing,Python,Python 2.7,Logging,Multiprocessing,因此,我尝试在多处理上下文中使用日志记录。假设我想让每个进程编写自己的日志文件。以下是我的设置: # worker.py import logging import os def worker( x ) : """ Write the value of x in the log file """ logger = logging.getLogger( __name__ ) pid = os.getpid() # get the process id
多处理
上下文中使用日志记录
。假设我想让每个进程编写自己的日志文件。以下是我的设置:
# worker.py
import logging
import os
def worker( x ) :
"""
Write the value of x in the log file
"""
logger = logging.getLogger( __name__ )
pid = os.getpid() # get the process id
handler = logging.FileHandler( str(pid) + ".log" )
logger.addHandler( handler )
logger.info( "pid={pid}, x={x}".format( **locals() ) )
这是我的main
:
import logging
import multiprocessing as mp
import worker
# logger
logger = logging.getLogger()
logger.setLevel( logging.INFO )
# handler
handler = logging.FileHandler( 'main.log' )
logger.addHandler( handler )
#
if __name__ == '__main__' :
pool = mp.Pool( processes=2 )
pool.map( worker.worker, range(5) )
pool.close()
pool.join()
现在是输出日志文件。这是main.log
:
pid=1985, x=0
pid=1985, x=2
pid=1986, x=1
pid=1985, x=3
pid=1986, x=4
我认为这种输出是正常的:两个子进程将事件传播到根父进程。因此,它确实不对应于场景(是吗?)。但现在是第一个子进程日志文件:
pid=1985, x=0
pid=1985, x=2
pid=1985, x=2
pid=1985, x=3
pid=1985, x=3
pid=1985, x=3
pid=1986, x=1
pid=1986, x=4
pid=1986, x=4
这是第二个子日志文件:
pid=1985, x=0
pid=1985, x=2
pid=1985, x=2
pid=1985, x=3
pid=1985, x=3
pid=1985, x=3
pid=1986, x=1
pid=1986, x=4
pid=1986, x=4
看起来每个子进程为第一次输入写一次日志,第二次写两次日志,第三次写三次日志,等等。发生了什么事?这是因为每次输入
worker
,都会得到对同一logger
对象的引用,然后向其添加一个新的FileHandler
。因此,如果调用了三次worker
,那么它的logger
将有三个filehandler
,它们恰好都写入同一个文件。启动时,应使用初始值设定项
关键字参数在每个池
进程中设置一次记录器:
def init( ) :
logger = logging.getLogger( __name__ )
pid = os.getpid() # get the process id
handler = logging.FileHandler( str(pid) + ".log" )
logger.addHandler( handler )
然后像这样启动游泳池
p = multiprocessing.Pool(processes=2, initializer=init)
然后,工作人员只需抓取
logger
对象并使用它,而无需向其添加FileHandler
之所以会发生这种情况,是因为每次输入worker
,都会得到对同一logger
对象的引用,然后向该对象添加新的FileHandler
。因此,如果调用了三次worker
,那么它的logger
将有三个filehandler
,它们恰好都写入同一个文件。启动时,应使用初始值设定项
关键字参数在每个池
进程中设置一次记录器:
def init( ) :
logger = logging.getLogger( __name__ )
pid = os.getpid() # get the process id
handler = logging.FileHandler( str(pid) + ".log" )
logger.addHandler( handler )
然后像这样启动游泳池
p = multiprocessing.Pool(processes=2, initializer=init)
然后,工作人员只需抓取logger
对象并使用它,而无需向其添加FileHandler