如何使用自定义日志记录处理程序将记录器重定向到wxPython textCtrl? [英] How can I redirect the logger to a wxPython textCtrl using a custom logging handler?

查看:171
本文介绍了如何使用自定义日志记录处理程序将记录器重定向到wxPython textCtrl?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python应用程序中使用了一个模块,该模块使用日志记录模块编写了大量消息.最初,我是在控制台应用程序中使用它的,使用控制台处理程序将日志输出显示在控制台上非常容易.现在,我已经使用wxPython开发了应用程序的GUI版本,并且希望将所有日志记录输出显示到自定义控件(多行textCtrl)中.有没有一种方法可以创建自定义日志记录处理程序,以便可以重定向所有日志记录输出并在需要的位置/位置显示日志记录消息-在这种情况下,是wxPython应用程序.

I'm using a module in my python app that writes a lot a of messages using the logging module. Initially I was using this in a console application and it was pretty easy to get the logging output to display on the console using a console handler. Now I've developed a GUI version of my app using wxPython and I'd like to display all the logging output to a custom control — a multi-line textCtrl. Is there a way i could create a custom logging handler so i can redirect all the logging output there and display the logging messages wherever/however I want — in this case, a wxPython app.

推荐答案

创建处理程序

import wx
import wx.lib.newevent

import logging

# create event type
wxLogEvent, EVT_WX_LOG_EVENT = wx.lib.newevent.NewEvent()


class wxLogHandler(logging.Handler):
    """
    A handler class which sends log strings to a wx object
    """
    def __init__(self, wxDest=None):
        """
        Initialize the handler
        @param wxDest: the destination object to post the event to 
        @type wxDest: wx.Window
        """
        logging.Handler.__init__(self)
        self.wxDest = wxDest
        self.level = logging.DEBUG

    def flush(self):
        """
        does nothing for this handler
        """


    def emit(self, record):
        """
        Emit a record.

        """
        try:
            msg = self.format(record)
            evt = wxLogEvent(message=msg,levelname=record.levelname)            
            wx.PostEvent(self.wxDest,evt)
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)

然后由您控制

self.Bind(EVT_WX_LOG_EVENT, self.onLogEvent)

def onLogEvent(self,event):
    '''
    Add event.message to text window
    '''
    msg = event.message.strip("\r")+"\n"
    self.logwindow.AppendText(msg) # or whatevery
    event.Skip()

这篇关于如何使用自定义日志记录处理程序将记录器重定向到wxPython textCtrl?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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