How to direct python logger to Tkinker Listbox?

I have a simple application with a class representing a data structure and a class for a graphical interface. I use the logger inside the first class:

class A(object):
    def __init__(self):
        self.logger = logging.getLogger(self.__class__.__name__)
        self.logger.info('creating new A object')

and etc.

The GUI consists of a single Tkinter window with a list.

How can I manage the logs in the list? I would like messages to populate the list as they are logged, not displayed in the console or log file.

How to update the list while the method is running inside the class?

+5
source share
1 answer

in this case, it is probably best to implement your own journal. Handler:

from logging import Handler, getLogger

class ListboxHandler(Handler):
    def __init__(self, box):
        self._box = box
        Handler.__init__(self)

    def emit(self, record):
        r = self.format(record)
        self._box.insert(0, r)

# quick test:
target = [] # supports insert like Listbox :)
rootLogger = getLogger()
# add handler to the root logger here
# should be done in the config...
rootLogger.addHandler(ListboxHandler(target))
rootLogger.warn('test')
print(target)

Thus, you have full control over formatting, log levels, etc. from your configuration.

+5
source

All Articles