多進程的日誌和多線程的日誌有一點區別。緣由是 Python 的 logging 包不支持進程共享鎖,因此來自不一樣的進程的日誌可能會混在一塊兒。咱們嘗試一下在上邊的例子里加一個基礎日誌。下邊是代碼:html
import loggingimport multiprocessingfrom multiprocessing import Process, Lockdef printer(item, lock): """ Prints out the item that was passed in """ lock.acquire() try: print(item) finally: lock.release()if __name__ == '__main__': lock = Lock() items = ['tango', 'foxtrot', 10] multiprocessing.log_to_stderr() logger = multiprocessing.get_logger() logger.setLevel(logging.INFO) for item in items: p = Process(target=printer, args=(item, lock)) p.start()
記錄日誌最簡單的方法是將全部的日誌發送給 stderr 。咱們能夠經過調用函數 log_to_stderr 來實現。而後咱們調用 get_logger 函數獲得記錄器(logger),並把日誌級別設置爲 INFO。剩下的代碼和原來同樣。這裏要說明一下,我並無用 join() 函數。相反, 父線程在退出的時候要顯式地調用 join()。python
當你運行上邊的代碼,會獲得像下面這樣的輸出:多線程
[INFO/Process-1] child process calling self.run() tango [INFO/Process-1] process shutting down [INFO/Process-1] process exiting with exitcode 0 [INFO/Process-2] child process calling self.run() [INFO/MainProcess] process shutting down foxtrot [INFO/Process-2] process shutting down [INFO/Process-3] child process calling self.run() [INFO/Process-2] process exiting with exitcode 0 10 [INFO/MainProcess] calling join() for process Process-3 [INFO/Process-3] process shutting down [INFO/Process-3] process exiting with exitcode 0 [INFO/MainProcess] calling join() for process Process-2
如今你若是想把日誌保存到硬盤,其實還有有些複雜的。你能夠參考 Python 的官方實例。ide