Search code examples
pythonloggingcursesintercept

How to manage logging in curses


I created a simple UI for my application using curses and I also include logs (logging) in my modules using herarchy structure (logmain, logmain.child1) and so on.

In case an log event occurs the log is displayed in my UI,distroying its apparence. I also created a pad (myLogPad) in order toput there the incoming logs, but without success. How I can intercept the log event and print it in a specific area (last line) of my screen?

def setupLogger(name,file_name):
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
#formatter = logging.Formatter(
#    "%(asctime)s %(threadName)-11s %(levelname)-10s %(message)s")
formatter = logging.Formatter('%(asctime) -25s - %(name) -15s - %(levelname) -10s - %(message)s')
formatterDisplay = logging.Formatter('%(asctime)-8s|%(name)-12s|%(levelname)-6s|%(message)-s', '%H:%M:%S')
# Alternative formatting available on python 3.2+:
# formatter = logging.Formatter(
#     "{asctime} {threadName:>11} {levelname} {message}", style='{')

# Log to file
filehandler = logging.FileHandler(file_name, 'w')

filehandler.setFormatter(formatter)
logger.addHandler(filehandler)

# Log to stdout too
streamhandler = logging.StreamHandler()

streamhandler.setFormatter(formatterDisplay)
logger.addHandler(streamhandler)

I try to pass mylog pad in the streamhandler = logging.StreamHandler() but without sucess. Any idea? Thank you


Solution

  • You can create your own Handler class to emit log messages to a curses pad or window:

    try:
        unicode
        _unicode = True
    except NameError:
        _unicode = False
    
    class CursesHandler(logging.Handler):
        def __init__(self, screen):
            logging.Handler.__init__(self)
            self.screen = screen
        def emit(self, record):
            try:
                msg = self.format(record)
                screen = self.screen
                fs = "\n%s"
                if not _unicode: #if no unicode support...
                    screen.addstr(fs % msg)
                    screen.refresh()
                else:
                    try:
                        if (isinstance(msg, unicode) ):
                            ufs = u'\n%s'
                            try:
                                screen.addstr(ufs % msg)
                                screen.refresh()
                            except UnicodeEncodeError:
                                screen.addstr((ufs % msg).encode(code))
                                screen.refresh()
                        else:
                            screen.addstr(fs % msg)
                            screen.refresh()
                    except UnicodeError:
                        screen.addstr(fs % msg.encode("UTF-8"))
                        screen.refresh()
            except (KeyboardInterrupt, SystemExit):
                raise
            except:
                self.handleError(record)
    

    (This was basically copied from logging.StreamHandler.) The window or pad needs to be initialized to allow automatic scrolling etc.:

    screen.nodelay(1)
    maxy, maxx = screen.getmaxyx()
    begin_x = 2; begin_y = maxy-5
    height = 5; width = maxx-4
    win = curses.newwin(height, width, begin_y, begin_x)
    curses.setsyx(-1, -1)
    screen.addstr("Testing my curses app")
    screen.refresh()
    win.refresh()
    win.scrollok(True)
    win.idlok(True)
    win.leaveok(True)
    mh = CursesHandler(win)
    mh.setFormatter(formatterDisplay)
    logger.addHandler(mh)
    

    Here, screen is the main curses screen.