Skip to content
Tutorials Center
My learning

Topics

Lesson 54 of 72 ยท Testing, Quality and Production

Logging and Debugging

Learn how to log from a Flask app with app.logger, configure levels, handlers and formats, add request details to every line, and track errors in production.

When a Flask app runs on your laptop, you watch the terminal and fix what breaks. When it runs on a server, nobody is watching. The only record of what happened at 3 a.m. is the log. Good logging tells you which request failed, why, and what the app was doing just before.

Flask builds on Python's standard logging module. You get a ready-made logger, app.logger, and you decide where its messages go and how they look. In this lesson you'll write log messages at the right level, configure handlers and formats, attach the current request to every log line, capture unhandled exceptions, and see how error-tracking services fit in. The interactive debugger is covered too, but as a development tool only.

If you have never used the logging module on its own, skim Logging and Warnings first. The ideas (loggers, levels, handlers, formatters) are the same here.

How a log message travels

Every call such as app.logger.info("...") creates a record. The logger first checks the record's level against its own threshold and drops it if it is too low. Surviving records go to each handler, and each handler formats the record into text and writes it somewhere: the console, a file, a network service.

flowchart LR
    A["app.logger.info(...)"] --> B{"level >= logger level?"}
    B -- no --> X["dropped"]
    B -- yes --> C["handler(s)"]
    C --> D["filter (optional)"]
    D --> E["formatter"]
    E --> F["console / file / service"]

A record is filtered by level, passed to handlers, formatted and finally written.

app.logger is a normal logging.Logger. Its name is the name of your application (Flask("shop") gives a logger called shop). If you put the logger name in your format string, every line says which app produced it.

Log levels

Python has five standard levels. Choosing the right one is most of the skill.

Level Use it for
DEBUG Detail for developers: values, branches taken, SQL
INFO Normal events worth recording: a user signed up, an order was placed
WARNING Something odd that the app handled: a retry, a deprecated call
ERROR An operation failed; the request could not do its job
CRITICAL The app cannot continue: no database, no disk space

In production you usually set the threshold to INFO, so DEBUG lines cost almost nothing. In development you lower it to DEBUG. Flask does this for you: with app.debug on, an unset logger level becomes DEBUG.

Configuring logging with dictConfig

Flask adds a default handler that writes to the error stream only when you have not configured one yourself. To take control, call logging.config.dictConfig() before you create the app. The dictionary describes formatters, handlers and loggers in one place, which is easy to read and easy to load from a file.

Python Configure logging with dictConfig

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The debug line never appears because the shop logger is set to INFO. Change "level" to "DEBUG" and run again to see it. Notice the style of the calls: app.logger.info("order %s shown", order_id) passes the value as an argument instead of building the string with an f-string. Python only formats the message if the record survives the level check, so disabled DEBUG lines cost almost nothing.

Always pass values as arguments ("user %s", user_id) rather than f-strings. It is faster for suppressed messages, and log tools can group identical message templates together.

Logging exceptions

When a view raises an exception that nothing handles, Flask logs it for you at ERROR level with the full traceback, then returns a 500 Internal Server Error page. In your own try/except blocks, use app.logger.exception(). It is error() plus the current traceback, and it should be called inside the except block.

The traceback text is long and contains file paths, so the next example plugs in a small formatter that keeps only the exception type and message. In real life you want the whole traceback.

Python Unhandled and handled exceptions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the /crash output: Flask itself logged Exception on /crash [GET] through app.logger, which is why it reached our handler. The visitor sees only a generic 500 page, while you get the details.

Never log passwords, tokens, session cookies, full card numbers or other secrets, and think twice before logging whole request bodies. Logs are copied around, shipped to third parties and kept for months.

Putting the request into every log line

A line like could not parse 'abc' is much more useful with the method, path and a request ID attached. A logging filter can add those fields to every record, and the formatter can print them. Flask's request context helps: has_request_context() tells you whether a request is active, so the same filter works for background code, too.

A request ID ties together every line that belongs to one request. A before_request hook can create one and store it on g; see Hooks, Application Context and g for the details of those hooks.

Python Request-aware log lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Lines logged outside a request show a dash, so the formatter never fails on a missing field. The after_request hook acts as a tiny access log: one line per request with the final status. In production the web server usually writes a proper access log too, so you may prefer to log only slow or failing requests from Flask.

Where logs go in production

On your own machine, the console is enough. On a server, you have a few common choices:

  • stdout/stderr, collected by the platform. Containers, systemd and most hosting platforms capture whatever your process prints and route it to their log viewer. This is the simplest option and what the twelve-factor approach recommends.
  • Files with rotation. logging.handlers.RotatingFileHandler or TimedRotatingFileHandler write to a file and start a new one when it grows too large or a day ends, so the disk never fills. This needs a real filesystem, so it is read-only here:
Python
from logging.handlers import RotatingFileHandler

handler = RotatingFileHandler("app.log", maxBytes=1_000_000, backupCount=5)
  • Structured (JSON) logs. Printing one JSON object per line lets tools such as Loki, Elasticsearch or Datadog search by field. Python has no built-in JSON formatter, but a short Formatter subclass that calls json.dumps on a dict works fine.

Gunicorn has its own loggers (gunicorn.error and gunicorn.access). A common trick is to make Flask reuse gunicorn's handlers when you run under it, so everything ends up in one stream. Deployment shows the production setup.

The debugger and debug mode

During development you start the app with flask run --debug. Debug mode switches on two helpers:

  • The reloader restarts the server when you save a file.
  • The interactive debugger shows the traceback in the browser. You can open each stack frame and run Python code in it.

Because the debugger lets anyone who can reach the page run arbitrary code on your server, never enable debug mode on a public server. Werkzeug protects it with a PIN printed in the terminal, but a PIN is not a security boundary you should rely on. The debugger needs a real server and a browser, so you cannot try it in these examples.

Two settings matter in tests and when you want errors to reach you:

  • app.testing = True (or TESTING=True) makes exceptions propagate to the caller instead of turning into a 500 page, so a failing view fails the test with a real traceback.
  • PROPAGATE_EXCEPTIONS forces that behavior independently.

You can also debug the old-fashioned way: print(), or breakpoint() in a terminal-based flask run, which drops you into Python's pdb.

Tracking errors you were not watching

Logs are great when you go looking. An error tracker such as Sentry (or an open-source equivalent) goes one step further: it collects every unhandled exception, groups duplicates, records the request, user and release, and notifies you. Setup is usually a few lines at startup and requires an account and network access, so this snippet is read-only:

Python
import sentry_sdk

sentry_sdk.init(
    dsn="https://<key>@<host>/<project>",
    traces_sample_rate=0.0,
    send_default_pii=False,
)

The SDK hooks into Flask's error handling automatically. You can build the same idea yourself in miniature: a catch-all error handler that records the exception plus request details, gives the visitor an incident number and returns a friendly 500 response.

Python A tiny error tracker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A handler for Exception also catches HTTPException subclasses such as 404, which is fine for a demo but wrong for a real app. Real handlers should pass HTTP errors through untouched; Error Handling and Custom Error Pages shows how.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is app.logger.info("order %s shown", order_id) preferred over app.logger.info(f"order {order_id} shown")?

    With lazy formatting, Python builds the final string only for records that will actually be emitted. Suppressed messages cost almost nothing.
  2. 2. Where should dictConfig() be called so that Flask uses your logging setup instead of its default handler?

    Flask only installs its default handler when no handler is configured yet, so configure logging before creating the app.
  3. 3. Which call records an error message together with the traceback of the exception being handled?

    exception() logs at ERROR level and adds the current exception's traceback. It is meant to be called from an except block.
  4. 4. What is the main danger of running with the interactive debugger on a public server?

    The debugger can execute arbitrary Python in the stack frames of a failed request. It must never be enabled where untrusted people can reach it.

Summary

  • app.logger is a standard logging.Logger named after your app; configure it before creating the app, usually with dictConfig.
  • Pick levels deliberately: DEBUG for developers, INFO for normal events, WARNING, ERROR and CRITICAL for problems of rising severity.
  • Pass values as arguments, use app.logger.exception() inside except blocks, and never log secrets.
  • A logging filter plus has_request_context() and g puts the method, path and a request ID on every line.
  • In production, write logs to stdout or rotating files, consider JSON output, and use an error tracker such as Sentry to hear about failures you were not watching.
  • Use flask run --debug and the interactive debugger on your own machine only.

Next, make the app faster with Performance and Caching.