Get a thread uuid?

I've got a function call logger which records function calls and their args for testing purposes, but what I would like to attach is also the thread uuid that each function is being called from within so that I can link up multiple function calls from the same thread e.g. in the case a function has nested calls to other functions.

I can get the thread id with:

import threading
threading.currentThread().ident

But this id is just a number that is only unique in the time it's running. After it ends, another thread can then use that same number.
Is there any way that I can ensure all threads have uuids, and read this?

I've worked around this for now by setting the name of the thread to a uuid if it's not one already

e.g.

thread = threading.current_thread()
# set the thread name to a UUID if it isn't already
try:
	uuid.UUID(thread.name)
except ValueError:
	thread.setName(str(uuid.uuid4()))

uuid_ = thread.name
1 Like