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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With