Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Flask Logging

Logging is a very useful tool to avoid the need for manual debugging. It also can provide insight as to what happened in a session on the production server. During development you’ll be able to see the messages on the terminal where Flask runs. On the production server it can be saved in a log file for later review.

Flask is using the standard logging module.

There are several pre-defined levels of logging. You can use the specific functions to indicate the importance of each log message.

from flask import Flask
app = Flask(__name__)

# This is logged when the server starts
app.logger.debug('debug')
app.logger.info('info')
app.logger.warning('warning')

@app.route("/")
def main():
    app.logger.debug("Some debug message")
    app.logger.info("Some info message")
    app.logger.warning("Some warning message")
    app.logger.error("Some error message")
    return "Hello World!"


First run the applicaton without the --debug flag and observe that the minimum log-level is set to WARNING. By default the logger will only show WARNING and ERROR level log.

flask --app basic run

Then run the application with the -debug flag and observe that the log level is now configure to DEBUG level.

flask --app basic --debug run
import basic

def test_app():
    web = basic.app.test_client()

    rv = web.get('/')
    assert rv.status == '200 OK'
    assert rv.data == b'Hello World!'


# TODO: add tests to the other apps and check the output of the logs