簡體   English   中英

python logger多線程類

[英]python logger class for multithreading

我在自由項目中使用自己的記錄器類,以通過ftp訪問日志並檢查錯誤。 它為每個進程編寫一個單獨的文件,該文件通過os.getpid()函數輸出到stdout。 這對於python多進程庫很有用。 但是我比多處理更多地使用多線程,而且我不知道如何改進我的代碼以為輸出到stdout的每個線程編寫一個單獨的文件。

class Logger(object):
    def __init__(self, realstdout, path='logs/'):
        today = datetime.datetime.now().isoformat()
        if path[-1] != '/':
            path = path+'/'
        os.mkdir(path + today)

        self.pid = str(os.getpid())
        self.handler = open(path + today + '/' + self.pid + '.txt', 'w', buffering=0)
        self.stdout = realstdout

    def write(self, buf):
        if buf == '\n' or buf == '(Pdb)':
            return
        buf = buf.replace('\n', '#')
        self.handler.write("[{0}]  [{1}] ".format(datetime.datetime.today(), self.pid) + buf + "\n")
        self.stdout.write("[{0}] ".format(self.pid) + buf + "\n")

    def flush(self):
        pass

    def __del__(self):
        self.handler.close()

怎么做?

如果使用相同的策略,為每個工作程序記錄一個單獨的日志文件,則每個線程必須有某種標識符。 由於每個線程在同一進程中執行,因此它們都將具有相同的進程ID。

我相信您可以使用線程標識來標識它:

>>> threading.current_thread()
<_MainThread(MainThread, started 139944996378368)>
>>> threading.current_thread().ident
139944996378368

線程感知記錄器可能能夠使用以下方法創建唯一標識符:

self.pid = str(threading.current_thread().ident)

暫無
暫無

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

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