views:

2205

answers:

3

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  A: 

I saw examples of thread IDs like this:

class myThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        self.threadID = threadID
        ...

The threading module docs lists name attribute as well:

...

A thread has a name. 
The name can be passed to the constructor, 
and read or changed through the name attribute.

...

Thread.name

A string used for identification purposes only. 
It has no semantics. Multiple threads may
be given the same name. The initial name is set by the constructor.
The MYYN
+5  A: 

thread.get_ident() works, though thread is deprecated, or threading.current_thread() (or threading.currentThread() in older versions of Python).

Nicholas Riley
Well, that didn't turn out like I expected. 'threading.current_thread().name' gives me the unique information I needed. Thanks again.
Charles Anderson
Corrected your links Nicholas. I recently realised that if you hover over a title in the docs a little red symbol appears to the right. Copy+paste that for more specific links to the docs :-)
Jon Cage
Thanks. I was wondering where the permalinks had got to in the new documentation format.
Nicholas Riley
+2  A: 

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")
kraymer
I should probably bin my logging code and use this library instead.
Charles Anderson