简体   繁体   中英

How do I inherit from logging.Handler to log to a GtkTextView?

I am relatively new to Python and I'm developing my first Python GUI (slowly). One of the third-party modules I want to use uses Python's logging framework . I would like their logs to go to a GtkTextView . I know where their logger variable is, so can call logger.addHandler .

How do I inherit from logging.Handler correctly?

My implementation based on the source of StreamHandler is

class GtkTextViewHandler(logging.Handler):
  def __init__(self, tv):
    logging.Handler.__init__(self)
    self.tv = tv
    self.tbf = tv.get_buffer()
    self.formatter = None

  def emit(self, record):
    try:
      msg = self.format(record)
      fs  = "%s\n"
      self.tbf.insert(self.tbf.get_end_iter(), fs % msg)
      self.tv.scroll_to_iter(self.tv.get_end_iter(), 0.0, False, 0, 0)
    except:
      self.handleError(record)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM