scls scls - 4 months ago 11
Python Question

How to have several handlers using Logbook?

I'm using logbook to log message in a Python app but

import logbook

from logbook import Logger, StreamHandler, NullHandler

log = Logger('LogbookExample')

import sys
StreamHandler(sys.stdout).push_application()

NullHandler().push_application()

def main():
log.info('Hello, World!')

if __name__ == "__main__":
main()


doesn't work as I was expecting...
nothing appears. Like if
NullHandler
was replacing
StreamHandler


So I wonder how to have several handlers connected to app ?

Answer

The problem here is choosing NullHandler. It acts as a "black hole", swallowing all logs and not propagating them up the stack.

Stacking non-NullHandlers is easy:

StreamHandler(sys.stdout).push_application()
StreamHandler(sys.stderr, bubble=True).push_application()

The bubble keyword means the handler should continue propagation up the stack after handling the record.