在GUI和控制台上的python日志记录输出 [英] python logging output on both GUI and console

查看:1481
本文介绍了在GUI和控制台上的python日志记录输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出这个小片段:

import sys
import os
import logging
from PyQt5 import QtGui, QtWidgets, QtCore

log = logging.getLogger("Foo")
logging.basicConfig(
    level=logging.INFO, format='%(levelname)s: %(filename)s - %(message)s')
log.setLevel(logging.DEBUG)


class ConsolePanelHandler(logging.Handler):

    def __init__(self, parent):
        logging.Handler.__init__(self)
        self.parent = parent

    def emit(self, record):
        self.parent.write(self.format(record))


class Foo(QtWidgets.QWidget):

    def __init__(self, parent=None):
        QtWidgets.QWidget.__init__(self, parent)

        self.textEdit = QtWidgets.QTextEdit(self)
        self.textEdit.setLineWrapMode(QtWidgets.QTextEdit.NoWrap)
        self.textEdit.setTextInteractionFlags(QtCore.Qt.TextSelectableByMouse)

        vbox = QtWidgets.QVBoxLayout()
        self.setLayout(vbox)
        vbox.addWidget(self.textEdit)

    def write(self, s):
        self.textEdit.setFontWeight(QtGui.QFont.Normal)
        self.textEdit.append(s)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    console_panel = Foo()
    handler = ConsolePanelHandler(console_panel)
    log.addHandler(handler)

    log.info("Getting logger {0} - {1}".format(id(log), log.handlers))
    [log.debug("This is normal text " + str(i)) for i in range(5)]
    console_panel.show()

    sys.exit(app.exec_())

问题:

  • 为什么将日志同时写入控制台和gui?据我所知log.handlers len应该只有1.
  • 我如何只写禁止控制台消息的gui?
  • 为什么gui格式不是basicConfig指定的格式?
  • Why is log writing to both the console and gui? As far as i know log.handlers len should be only 1.
  • How can i write only to the gui supressing the console messages?
  • Why the gui format is not the one specified by basicConfig?

推荐答案

您的问题是由于在导入时调用basicConfig()引起的-如

Your problem is caused by calling basicConfig() at import time - as documented, this adds a console logger to the root logger if it doesn't have any handlers already.

您需要删除此调用并在if __name__ == '__main__'子句中添加一行:

You need to remove this call and add a line in the if __name__ == '__main__' clause:

handler.setFormatter(logging.Formatter('%(levelname)s: %(filename)s - %(message)s'))

然后您应该获得预期的结果.

and you should then get the result you were expecting.

您看到这两种消息的原因是,信息在记录器和处理程序之间如何流动,这在文档此处.

The reason you saw both messages is because how information flows between loggers and handlers, which is described in the documentation here.

这篇关于在GUI和控制台上的python日志记录输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆