When your Flask API runs in production, you need to know how long each request takes and what status code it returns — without writing logging.info(...) manually in every view. The solution is two built-in Flask hooks: before_request runs before each view to start a timer, and after_request runs after the view to log the result with the processing time and status code. Write it once, and the whole app gets logged automatically — ideal when you need basic request observability without building a heavy APM system yet.
The Problem
A familiar situation: users report the API is “slow”, but you can’t tell which route is slow because no log records the processing time. What many people do at first is insert timing code into every view:
import time, loggingfrom flask import Flask, request, jsonifyapp = Flask(__name__)logging.basicConfig(level=logging.INFO)@app.get("/orders")def list_orders(): start = time.perf_counter() # repeated in every view data = get_orders_from_db() logging.info("GET /orders 200 %.1fms", (time.perf_counter() - start) * 1000) return jsonify(data)
The problem: every view repeats 3 lines of timing and logging code; miss one view and you lose the trail; want to change the log format and you have to edit dozens of places. The more routes you have, the messier and more error-prone the code gets.
The Solution
Flask provides two hooks that wrap every request. Start the timer in before_request, write the log in after_request:
import time, loggingfrom flask import Flask, request, gapp = Flask(__name__)logging.basicConfig(level=logging.INFO)log = logging.getLogger("requests")@app.before_requestdef start_timer(): g.start = time.perf_counter() # g: per-request storage@app.after_requestdef log_request(response): ms = (time.perf_counter() - g.start) * 1000 log.info("%s %s -> %s (%.1f ms)", request.method, request.path, response.status_code, ms) return response # MUST return the response
Why this is better: first, write once, apply to the whole app — new routes need no extra work. Second, g is a per-request object (context-local), so timing stays safe when many requests run concurrently. Third, all log formatting lives in one function; changing the format means editing one place.
Bonus: before_request can also “stop” a request right at the gate. If the hook function returns a response, Flask uses it as the final result and skips the view — very handy for a centralized maintenance mode:
from flask import jsonify@app.before_requestdef maintenance_mode(): if app.config.get("MAINTENANCE") and request.path.startswith("/api"): return jsonify({"error": "system under maintenance"}), 503
Apply It to Your Project
Turn on these two hooks in your app factory today: log to the console in dev, to a file or a centralized logging system in production. When you see a route regularly exceeding 500ms, you now have concrete data to dig into instead of guessing. Later, when you want to upgrade to real APM (Sentry, Datadog…), just swap the log.info line for their client — no per-view changes needed.
Related Posts
- Flask: Managing Login with Flask-Login — login_required and remember me in 5 Minutes — checking login right inside
before_requestis the natural next step once you’re comfortable with hooks. - Flask: Secure File Uploads — Validate File Types and Limit Size in 5 Minutes — slow upload requests will show up immediately in the timing log.
- Flask: Sending Email with Flask-Mail — Don’t Let SMTP Block Your Requests (5 Minutes) — combine timing logs to catch mail-sending routes slowing down responses.
Frequently Asked Questions
How is before_request different from middleware?
WSGI middleware wraps the whole app and operates at a low level (including static files), while before_request is a Flask hook that only runs for requests going through Flask’s routing. The hook is written in plain Python, so it’s easier to read and test than WSGI middleware.
Is the g object safe with concurrent requests?
Yes. g is context-local: each request owns its own g, and one request cannot read another request’s g — even when the server runs multi-threaded.
Does after_request run when the view raises an exception?
No. If the view raises an unhandled exception, Flask skips after_request. To log error cases too, add @app.teardown_request — that hook always runs, even on exceptions.
If before_request returns a response, does the view still run?
No. Flask uses that response as the final result and skips the view entirely. That’s exactly the mechanism for maintenance mode or centralized API-key checks.
Can I register hooks on a blueprint?
Yes. @bp.before_request only applies to routes in that blueprint — useful when you want separate logging for the admin module or the API module.
References
- Flask documentation — Request hooks (before_request / after_request): flask.palletsprojects.com
- Pallets Projects — Application context
g: flask.palletsprojects.com
