After last week’s first steps with logging, it is now time to add logging to our Flask application.
This post is part of my journey to learn Python. You can find the other parts of this series here.
Built-in logger in Flask
Flask uses the standard Python logging, what allows us to write log messages in the same way as we do in our Python scripts. All we need to change is to use app.logger instead of logging:
1 2 3 4 5 6 7 8 |
@app.route('/') def index(): app.logger.debug("A log message in level debug") app.logger.info("A log message in level info") app.logger.warning("A log message in level warning") app.logger.error("A log message in level error") app.logger.critical("A log message in level critical") return "Hello world!" |
You can find your log messages next to the ones from Flask:
127.0.0.1 – – [22/Feb/2021 19:17:52] “GET /contact HTTP/1.1” 200 –
127.0.0.1 – – [22/Feb/2021 19:17:52] “GET /static/css/contact.css HTTP/1.1” 200 –
[2021-02-22 19:28:37,619] DEBUG in hello: A log message in level debug
[2021-02-22 19:28:37,620] INFO in hello: A log message in level info
[2021-02-22 19:28:37,621] WARNING in hello: A log message in level warning
[2021-02-22 19:28:37,624] ERROR in hello: A log message in level error
[2021-02-22 19:28:37,625] CRITICAL in hello: A log message in level critical
Flask uses a slightly different log format that includes the file name in the message – in my case hello for hello.py.
Logging in Blueprint
If you use Blueprint to clean-up the view functions file you need a little bit more work. When you replace app with blueprint and try to log you get this error:
AttributeError: ‘Blueprint’ object has no attribute ‘logger’
For the parts of our application that use Blueprint we need to import current_app from flask and use the logger that is available there:
1 2 3 4 5 6 7 8 9 10 11 |
import flask from flask import render_template, request from hello_flask.viewmodels.contact_viewmodel import ContactViewModel from flask import current_app blueprint = flask.Blueprint('contact', __name__, template_folder='templates') @blueprint.route('/contact', methods=['GET']) def contact_form(): current_app.logger.info("Contact form loaded") return render_template('contact/contact.html') |
What we write to current_app.logger ends up in the same place as our log messages from app.logger:
[2021-02-22 19:17:52,904] INFO in contact_views: Contact form loaded
Next
As you can see, logging in Flask is nearly the same as in Python. Only Blueprint has its own challenge that we can solve with the import of current_app. Before I start to configure the Flask logger, I make a small detour to structured logging and Seq as a centralised log server.
1 thought on “Python Friday #63: Logging in Flask”