2014-04-10 136 views
0

如何讓我的兩個進程登錄一個唯一的文件? 我的代碼只有PROC1被記錄到我的日誌文件... module.py:Python 2.7多處理日誌和循環

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() 

回答

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