Xavier V. Xavier V. - 1 year ago 130
Python Question

How to set the name of a QThread in pyqt?

I am using


To log, I am also using the following formatter :

logging.Formatter('%(levelname)-8s %(asctime)s %(threadName)-15s %(message)s')

The resulting log is :

DEBUG 2012-10-01 03:59:31,479 Dummy-3 my_message

My problem is that I want to know more explicitly which thread is logging...
is not the most explicit name to me....

Is there a way to set a name to a
that will be usable by the logging module (as a LogRecord attribute) in order to have a log more meaningful ?

Thanks !

Answer Source

If the threading module is available, the logging module will use threading.current_thread().name to set the threadName LogRecord attribute.

But the docs for threading.current_thread say that a dummy thread object will be used if the current thread was not created by the threading module (hence the "Dummy-x" name).

I suppose it would be possible to monkey-patch threading.current_thread to reset the name to something more appropriate. But surely a much better approach would be to make use of the extra dictionary when logging a message:

logging.Formatter('%(levelname)-8s %(asctime)s %(qthreadname)-15s %(message)s')
extras = {'qthreadname': get_qthreadname()}
logging.warning(message, extra=extras)