How to Redirect Logger Output into PyQt Text Widget

You can create a custom logging.Handler and add it to your logger:

import logging
logger = logging.getLogger(__name__)

class QtHandler(logging.Handler):

    def __init__(self):
        logging.Handler.__init__(self)

    def emit(self, record):
        record = self.format(record)
        XStream.stdout().write("{}\n".format(record))

handler = QtHandler()
handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)

Then remove the logging.basisConfig(level=logging.DEBUG) line in the if __name__ == "__main__": block. You'll see your log messages only appear in your dialog box.


The answer given by dano works for 2.7.x, but not for 3.x.

To get the code provided by @dano working in 3.4.3 I had to make the obvious changes to the print statements and also change the write() method in the XStream class from self.messageWritten.emit(unicode(msg)) to self.messageWritten.emit(msg). That unicode call just made the dialog sit there and stare back at me in amusement.

Tags:

Python

Pyqt