Python: How to make Flask work with Logbook

By | July 24, 2017

If you’ve arrived at this page, it’s probably because you’re searching the web for an answer why, even though you’ve called logbook.compat.redirect_logging() in your Python Flask app, you’re still not getting any Flask logging in your log files.

The problem is that Flask sets the propagate flag on its logger to False by default, so even though Logbook’s redirect_logging() method installs a handler on the root logger to redirect messages to Logbook, Flask’s log messages never make it to that handler because they are stopped at Flask’s handler.

The fix is simple: after creating your Flask app, tell it to propagate logging events:

app.logger.propagate = True

But wait, there’s more.

In addition to setting the propagate flag on its logger to False, flask also installs a handler on that logger. That handler behaves as follows: if Flask is running in production mode, i.e., Flask debugging isn’t enabled, then log nothing at any level. Otherwise, print all log messages to sys.stderr.

The odds are that if you’re trying to redirect Flask’s logging to Logbook, then neither of those behaviors is what you want. You want Flask’s logging to go to your Logbook handlers rather than sys.stderr, and you want your Logbook handlers and loggers to control the logging level. To achieve all of this, you need to (a) call logbook.compat.redirect_logging() as mentioned above, (b) set app.logger.propagate = True as mentioned above, and finally (c) remove the handler installed by Flask:

del app.logger.handlers[:]

If this tip is useful to you, post a comment below and let me know!


Print Friendly, PDF & Email

Leave a Reply

Your email address will not be published. Required fields are marked *