Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to direct python logger to Tkinker's Listbox?

I have a simple app with a class representing a data structure and a class for GUI. I use a 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')

etc.

The GUI consists in one Tkinter window with a Listbox.

How can I direct the logs to the listbox? I would like to see the messages populate the list instead as they get logged instead of showing up in the console or log file.

How can I update the listbox while a method within the class is executed?

like image 346
user1156980 Avatar asked Apr 25 '12 08:04

user1156980


People also ask

What is logging basicConfig in Python?

Python logging basicConfig The basicConfig configures the root logger. It does basic configuration for the logging system by creating a stream handler with a default formatter. The debug , info , warning , error and critical call basicConfig automatically if no handlers are defined for the root logger.

What is logger Setlevel Python?

The level set in the logger determines which severity of messages it will pass to its handlers. The level set in each handler determines which messages that handler will send on." Check under Handlers: http://docs.python.org/2.7/howto/logging.html#logging-advanced-tutorial.

What is logger getLogger in Python?

The getLogger() function accepts a single argument - the logger's name. It returns a reference to a logger instance with the specified name if provided, or root if not. Multiple calls to getLogger() with the same name will return a reference to the same logger object.


1 Answers

in this case it's probably best to implement your own logging.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)

this way you have full control over formatting, log levels etc. from your config.

like image 63
mata Avatar answered Sep 28 '22 01:09

mata