python 在gui中显示logging_在GUI和控制台上的python日志记录输出

1586010002-jmsa.png

Given this little snippet:

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_())

Questions:

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?

解决方案

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.

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.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值