2016-11-30 45 views
1

如何將日誌輸出到多個進程的控制檯? 例子:多處理中的Python日誌

import multiprocessing, logging, multiprocessing_logging 

logging.basicConfig(level=logging.INFO) 
logger = logging.getLogger() 
multiprocessing_logging.install_mp_handler(logger) 

def worker(): 
    while True: 
     logger.info("This is logging for TEST1") 

def worker2(): 
    while True: 
     logger.info("This is logging for TEST2") 

if __name__ == '__main__': 
    p1 = multiprocessing.Process(target=worker) 
    p1.daemon = True 
    p1.start() 

    p2 = multiprocessing.Process(target=worker2) 
    p2.daemon = True 
    p2.start() 

    p1.join() 
    p2.join() 

但輸出不正確:

INFO:root:This is logging for TEST1 
INFO:root:This is logging for TEST2 
IINFO:root:This is logging for TEST1 
NFO:root:This is logging for TEST2 
INFO:root:This is logging for TEST1 
INFO:root:This is logging for TEST2 
INFO:root:This is logging for TEST1 
IINFO:root:This is logging for TEST2 
NFO:root:This is logging for TEST1 
IINFO:root:This is logging for TEST2 
NFO:root:This is logging for TEST1 

我試圖用multiprocessing-logging庫,但它並沒有幫助

+0

'multiprocessing-logging'看起來應該可以解決你的問題 - 你能否提供一個[MCVE]來顯示當你使用它時不起作用? –

+0

我只是導入多處理日誌記錄並添加multiprocessing_logging.install_mp_handler()配置日誌後,像寫它[鏈接](https://github.com/jruere/multiprocessing-logging#usage) – deniska369

+0

在這種情況下,你應該[文件一個錯誤報告](https://github.com/jruere/multiprocessing-logging/issues/new)與'multiprocessing-logging'。 –

回答

1

你(更新)代碼工作正常,在這裏:

INFO:root:This is logging for TEST1 
INFO:root:This is logging for TEST1 
INFO:root:This is logging for TEST1 
INFO:root:This is logging for TEST1 
INFO:root:This is logging for TEST1 
INFO:root:This is logging for TEST1 
INFO:root:This is logging for TEST1 
INFO:root:This is logging for TEST1 
INFO:root:This is logging for TEST1 
INFO:root:This is logging for TEST2 
INFO:root:This is logging for TEST1 
INFO:root:This is logging for TEST1 
INFO:root:This is logging for TEST2 
INFO:root:This is logging for TEST2 
INFO:root:This is logging for TEST2 
INFO:root:This is logging for TEST2 
INFO:root:This is logging for TEST2 
INFO:root:This is logging for TEST2 
INFO:root:This is logging for TEST2 
INFO:root:This is logging for TEST2 
INFO:root:This is logging for TEST2 
INFO:root:This is logging for TEST2 
INFO:root:This is logging for TEST2 
INFO:root:This is logging for TEST2 
INFO:root:This is logging for TEST2 
INFO:root:This is logging for TEST2 

如果它不適合你,那麼你應該file a bug report with multiprocessing-logging

+0

'IINFO:root:這是記錄TEST2 NFO:root:這是記錄TEST1' 不爲我工作 – deniska369

+0

非常感謝! – deniska369