Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the name of a QThread in pyqt?

I am using QtCore.QThread (from PyQt4).

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... Dummy-3 is not the most explicit name to me....

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

Thanks !

like image 375
Xavier V. Avatar asked Oct 01 '12 03:10

Xavier V.


1 Answers

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)
like image 55
ekhumoro Avatar answered Sep 27 '22 17:09

ekhumoro