How to find a thread id in Python


Question

I have a multi-threading Python program, and a utility function, writeLog(message), that writes out a timestamp followed by the message. Unfortunately, the resultant log file gives no indication of which thread is generating which message.

I would like writeLog() to be able to add something to the message to identify which thread is calling it. Obviously I could just make the threads pass this information in, but that would be a lot more work. Is there some thread equivalent of os.getpid() that I could use?

1
145
8/25/2019 2:48:18 AM

Accepted Answer

threading.get_ident() works, or threading.current_thread().ident (or threading.currentThread().ident for Python < 2.6).

188
3/24/2019 10:08:14 AM

Using the logging module you can automatically add the current thread identifier in each log entry. Just use one of these LogRecord mapping keys in your logger format string:

%(thread)d : Thread ID (if available).

%(threadName)s : Thread name (if available).

and set up your default handler with it:

logging.basicConfig(format="%(threadName)s:%(message)s")

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon