Python 2.7多处理日志记录和循环

时间:2014-04-10 18:23:46

标签: python python-2.7 multiprocessing

如何让我的两个进程只登录一个文件? 使用我的代码只有proc1登录到我的日志文件... module.py:

import multiprocessing,logging

log = multiprocessing.log_to_stderr()
log.setLevel(logging.DEBUG)
handler = logging.FileHandler('/var/log/my.log')
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
log.addHandler(handler)

def proc1():
    log.info('Hi from proc1')
    while True:
        if something:
            log.info('something')

def proc2():
    log.info('Hi from proc2')
    while True:
        if something_more:
             log.info('something more')

if __name__ == '__main__':
    p1 = multiprocessing.Process(target=proc1)
    p2 = multiprocessing.Process(target=proc2)
    p1.start()
    p2.start()

1 个答案:

答案 0 :(得分:2)

https://docs.python.org/2/howto/logging-cookbook.html#logging-to-a-single-file-from-multiple-processes

所述
  

"虽然日志记录是线程安全的,但是从日志记录到单个文件   支持单个进程中的多个线程,记录到单个进程   不支持来自多个流程的文件"

然后,你应该找到另一种方法来实现它,即实现一个日志记录服务器:

https://docs.python.org/2/howto/logging-cookbook.html#sending-and-receiving-logging-events-across-a-network