簡體   English   中英

Python 創建多個日志文件

[英]Python create multiple log files

我正在使用批處理並在 function 下面並行調用。 我需要為每個進程創建新的日志文件

下面是示例代碼

導入日志

def processDocument(inputfilename): logfile=inputfilename+'.log'

logging.basicConfig( 
filename=logfile, 
level=logging.INFO)

//performing some function

logging.info("process completed for file")
logging.shutdown()

它正在創建日志文件。 但是當我批量通過這個 function 調用 20 次時。 僅創建了 16 個日志文件。

這些問題可能發生在線程競爭條件下。

如果文檔處理彼此獨立,我建議通過高級 class concurrent.futures.ProcessPoolExecutor使用multiprocessing

如果您想堅持使用線程,因為文檔處理更多的是 I/O 綁定,則可以使用concurrent.futures.ThreadPoolExecutor ,它提供相同的接口但帶有線程。

最后但同樣重要的是,像這個玩具示例(使用標准threading庫)一樣正確配置您的logging

import logging
from sys import stdout
import time 
import threading

def processDocument(inputfilename:str):
    logfile = inputfilename + '.log'
    this_thread = threading.current_thread().name

    this_thread_logger = logging.getLogger(this_thread)

    file_handler = logging.FileHandler(filename=logfile)
    out_handler = logging.StreamHandler(stdout)

    file_handler.level = logging.INFO
    out_handler.level = logging.INFO

    this_thread_logger.addHandler(file_handler)
    this_thread_logger.addHandler(out_handler)

    this_thread_logger.info(f'Processing {inputfilename} from {this_thread}...')
    time.sleep(1) # processing
    this_thread_logger.info(f'Processing {inputfilename} from {this_thread}... Done')
    

def main():
    filenames = ['hello', 'hello2', 'hello3']

    threads = [threading.Thread(target=processDocument, args=(name,)) for name in filenames]
    
    for thread in threads:
        thread.start()

    for thread in threads:
        thread.join()

    logging.shutdown()

main()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM