[Python] 在 python 程式中取得 thread id

[Python] 在 python 程式中取得 thread id

 在寫 python 的時候,用了內建的 logging 機制在寫記錄檔,

但有個令人困擾的問題是,沒辦法顯示出真正的 thread id…

雖然 logging 的 format 可以指定像 thread ident 或 thread name,

但都不是真正的 thread id…

之前就暫時不理這問題,但最近發現,

在 multi-thread 的情況下要找問題時,沒有 thread id 的話,

會讓 debug log  的內容全都混在一起,分不出來哪個線程做了哪些事情…

 

找了一下,有人已經解決了這個問題:

FINDING THE LINUX THREAD ID FROM WITHIN PYTHON USING CTYPES

 

試了一下他的方法,也的確可以顯示出 thread id 了,

但為了避免每次寫一行記錄檔,就要呼叫一次 syscall() 拿 thread id,

我是把拿到的 thread id 先存在 threading.local() 裡面,

這樣如果這 thread 已經取過的話,就不用再取了~

try:
    # Get thread id from thread local storage.
    # If not exist yet, get it via syscall().
    record.thread = threading.local().threadid
except AttributeError:
    import ctypes
    libc = ctypes.cdll.LoadLibrary(‘libc.so.6’)
    SYS_gettid = 186
    record.thread = threading.local().threadid = libc.syscall(SYS_gettid)
 

 

 

//
//

(本頁面已被瀏覽過 1,400 次)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料