How to Redirect Logger Output into PyQt Text Widget

后端 未结 2 811
盖世英雄少女心
盖世英雄少女心 2020-12-25 08:44

A code posted on Redirecting Output in PyQt does two good things at once: it takes advantage of logging module to nicely format messages and it redirects standa

相关标签:
2条回答
  • 2020-12-25 09:09

    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.

    0 讨论(0)
  • 2020-12-25 09:10

    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.

    0 讨论(0)
提交回复
热议问题