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