Python logging module used in GUI - chicken and egg problem during start-up sequence

Hello,

Ive got a wx app which has a log widget, and when creating the frame, I
redirecting stdout to this widget using the python logging module. I cannot
redirect messages to this widget before the frame is created, and effectively
I cannot log messages appearing during the start-up sequence.

To me this seems like a classical chicken and egg problem, and I'm looking for
comments, suggestions and improvements to the following solution:

class OutputWindowStream(logging.Handler):
    def __init__(self):
        logging.Handler.__init__(self)
        self.textbox = None
        self.buffer = []

    def setTextBox(self, textbox):
        """
        textbox presents the instance of textctrl in the mainframe
        Method is called after frame is up and running
        """
        self.textbox = textbox

    def shouldFlush(self):
        if self.textbox:
            return True
        else:
            return False
    
    def emit(self, record):
        self.buffer.append(record)
        if self.shouldFlush():
            self.flush()

    def flush(self):
        """
        Thread safe flush method which schedule the
        textbox update after a wx main loop ends
        """
        for record in self.buffer:
            msg = self.format(record)
            wx.CallAfter(self.textbox.AppendText, msg+'\n')
        self.buffer = []

    def close(self):
        self.flush()
        self.textbox = None
        logging.Handler.close(self)

Frank Aune wrote:

Hello,

Ive got a wx app which has a log widget, and when creating the frame, I redirecting stdout to this widget using the python logging module. I cannot redirect messages to this widget before the frame is created, and effectively I cannot log messages appearing during the start-up sequence.

To me this seems like a classical chicken and egg problem, and I'm looking for comments, suggestions and improvements to the following solution:

It looks like what I would suggest doing. Something else you may want to consider is to also make it possible to get those early log messages if there is an exception in the frame init code and it is never displayed. Maybe writing it to stderr or something if there is anything in the buffer when the app exits.

···

--
Robin Dunn
Software Craftsman
http://wxPython.org Java give you jitters? Relax with wxPython!