Learn Flask · 13/15

Error Handling and Logging: Keeping Things Stable

7 min read

Hello, aspiring Flask developers! 👋

Let's talk about something that separates the hobbyists from the pros: what happens when things go wrong. A perfect, bug-free application is a beautiful dream, but in reality, servers fail, users input weird things, and code... well, code sometimes has a mind of its own. This is where error handling and logging come in. They are your application's seatbelt and black box recorder, ensuring that when a crash happens, it's a graceful bump, not a catastrophic explosion, and you have all the data to figure out why it happened.


1. Designing Custom Error Pages (404, 500) 🎨

The Problem: By default, when a user tries to access a page that doesn't exist (a 404 Not Found error) or when your code breaks unexpectedly (a 500 Internal Server Error), Flask shows a plain, generic, and frankly, boring error page. This can be jarring for users and makes your application feel unprofessional. It breaks the user experience and offers no helpful guidance, like a link back to the homepage.

The Solution: Flask allows you to create your own beautiful, branded error pages that match the look and feel of your site. The key to this magic is the @app.errorhandler() decorator.

Imagine you're a librarian. If someone asks for a book that doesn't exist, you don't just stare at them blankly. You politely say, "I'm sorry, we don't have that book, but you can check our catalog here or return to the main hall." That's what a custom 404 page does.

How it Works (Under the Hood):
When Flask encounters an error (like a 404 or 500), it pauses the normal request flow and checks if a special function has been registered to handle that specific error code. If it finds one, it executes your function instead of showing its default page.

Hands-on Industry Practice:
Let's create custom pages for the two most common errors: 404 Not Found and 500 Internal Server Error.

First, create the HTML template files inside your templates folder.

templates/404.html

html
{% extends "base.html" %}
{% block content %}
<div class="container">
    <h1>Oops! Page Not Found (404)</h1>
    <p>The page you are looking for does not exist. It might have been moved or deleted.</p>
    <a href="{{ url_for('index') }}">Go back to the homepage</a>
</div>
{% endblock %}

templates/500.html

html
{% extends "base.html" %}
{% block content %}
<div class="container">
    <h1>Yikes! Something went wrong (500)</h1>
    <p>We're experiencing some technical difficulties. Our team has been notified!</p>
    <a href="{{ url_for('index') }}">Go back to the homepage</a>
</div>
{% endblock %}

(Note: These assume you have a base.html they can extend for consistent styling).

Now, in your main application file (e.g., app.py), register these handlers.

app.py

python
from flask import Flask, render_template

app = Flask(__name__)

# A normal route
@app.route('/')
def index():
    return '<h1>Welcome to the main page!</h1>'

# Error handler for 404 Not Found
@app.errorhandler(404)
def page_not_found(e):
    # note that we set the 404 status code explicitly
    return render_template('404.html'), 404

# Error handler for 500 Internal Server Error
@app.errorhandler(500)
def internal_server_error(e):
    # note that we set the 500 status code explicitly
    return render_template('500.html'), 500

Now, if you run your app and navigate to a non-existent URL like /i-love-pizza, you'll see your custom 404.html page instead of the default one!


2. Global Exception Handling: Catching Unhandled Errors 🥅

The Problem: Custom pages for 404 and 500 errors are great, but what about all the other possible errors? TypeError, ValueError, KeyError, you name it. If your code divides by zero or tries to access a dictionary key that isn't there, Flask will default to a 500 Internal Server Error. You could wrap every line of code in try...except blocks, but that would be a nightmare.

The Solution: You need a "catch-all" safety net. You can create a global error handler that catches any exception that wasn't caught by a more specific handler. This is incredibly useful for ensuring that no matter what breaks, the user sees your friendly 500 page, and you get a chance to log the real error.

How it Works (Under the Hood):
Flask's error handling system is hierarchical. When an error occurs, it looks for the most specific handler first (e.g., @app.errorhandler(404)). If it doesn't find one, it looks for a handler for a more general class of error. By creating a handler for the base Exception class, you create a handler that will catch almost anything.

Hands-on Industry Practice:
Let's expand on our previous example. We'll add a route that deliberately causes an error and a global handler to catch it.

app.py

python
from flask import Flask, render_template

app = Flask(__name__)

# ... (index route and 404 handler from before) ...

# This route will cause a ZeroDivisionError
@app.route('/oops')
def trigger_error():
    result = 1 / 0
    return f'The result is {result}' # This line will never be reached

# A more generic handler for any unhandled exception
@app.errorhandler(Exception)
def handle_exception(e):
    # For now, we'll just show our generic 500 page.
    # In the next section, we will log the specific error e.
    return render_template("500.html"), 500

With this setup, visiting the /oops URL will no longer show the scary developer-focused debugger (in production mode). Instead, it will gracefully display your 500.html page, giving the user a much better experience.


3. Configuring Python Logging for Flask Applications 📝

The Problem: Showing a nice error page is for the user. But what about you, the developer? You need to know what went wrong. Simply showing a "Something went wrong" message is useless for debugging. Printing to the console works during development, but in a production environment, those print statements are lost forever.

The Solution: Use Python's built-in logging module. Flask integrates with it seamlessly via app.logger. Logging allows you to save detailed error messages, stack traces, and other important information to a file, so you can analyze it later to fix bugs.

Think of it as the black box of an airplane. When something goes wrong, investigators check the black box to get a detailed record of what happened right before the incident. Your log file is your application's black box.

How it Works (Under the Hood):
The logging module is a powerful system with three main components you should know:

  • Loggers: The entry point. You send your messages to a logger (e.g., app.logger.error(...)).
  • Handlers: These direct the log messages to a destination, like the console (StreamHandler) or a file (FileHandler).
  • Formatters: These control the layout of your log messages, so you can include useful information like a timestamp, the log level, and the message itself.

Hands-on Industry Practice:
The industry standard is to log errors to a file that can be monitored and analyzed. A RotatingFileHandler is often used to prevent log files from growing infinitely large.

Let's tie all our concepts together. We'll configure logging to a file and log the actual exception in our global error handler.

app.py

python
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask, render_template

app = Flask(__name__)

# --- Logging Configuration ---
# Configure logging before creating the app object if possible. [23]
# We'll set the log level to INFO to capture informational messages as well.
# In production, you might want to set this to WARNING or ERROR.
logging.basicConfig(level=logging.INFO)

# Create a file handler that logs even debug messages.
# We'll use a RotatingFileHandler to keep the log file size in check.
# It will create up to 10 backup files, each 1MB in size.
handler = RotatingFileHandler('app.log', maxBytes=1000000, backupCount=10)
handler.setLevel(logging.INFO)

# Create a log message format.
formatter = logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s [in %(pathname)s:%(lineno)d]'
)
handler.setFormatter(formatter)

# Add the handler to the app's logger.
app.logger.addHandler(handler)


# --- Routes and Error Handlers ---

@app.route('/')
def index():
    app.logger.info('Main page accessed successfully.')
    return '<h1>Welcome to the main page!</h1>'

@app.route('/oops')
def trigger_error():
    app.logger.warning('An attempt to trigger an error is being made.')
    result = 1 / 0
    return f'The result is {result}'

@app.errorhandler(404)
def page_not_found(e):
    app.logger.error(f'Page not found: {e}')
    return render_template('404.html'), 404

# Updated global exception handler to include logging
@app.errorhandler(Exception)
def handle_exception(e):
    # Log the full exception and stack trace
    app.logger.error(f'An unhandled exception occurred: {e}', exc_info=True)
    return render_template("500.html"), 500

Now, when you visit the /oops URL, the user still sees the friendly 500.html page. But if you look in your project directory, you'll find a new file named app.log. It will contain a detailed entry with a timestamp, the error message (division by zero), and a full stack trace pointing to the exact line of code that failed. Now you're not just handling errors gracefully—you're equipped to fix them! 🕵️‍♀️


References for Extra Reading:

Challenge

Challenge: Implement Robust Error Handling and Logging in Flask

Your task is to build a resilient Flask application by implementing comprehensive error handling and logging. You will create custom handlers for specific HTTP errors and a global handler for all other exceptions, while also configuring a production-ready logging setup.

Requirements:

  1. Application Setup: Your code should be a single, self-contained Flask application.

  2. Routes:

    • Create a root route / that successfully returns the string "Welcome to the Resilient App!".
    • Create a route /crash that intentionally raises a ZeroDivisionError by attempting the operation 1 / 0.
  3. Custom 404 Error Handler:

    • Implement a specific error handler for 404 Not Found errors.
    • When triggered, this handler must render the provided NOT_FOUND_TEMPLATE string and return a 404 status code.
  4. Global Exception Handler:

    • Implement a global error handler that catches any unhandled Exception.
    • This handler must perform two actions:
      1. Log the full exception details, including the stack trace, using the application's logger at the ERROR level.
      2. Render the provided INTERNAL_ERROR_TEMPLATE string and return a 500 status code.
  5. Logging Configuration:

    • Configure the application logger (app.logger) to write logs to a file.
    • Use a RotatingFileHandler for the file app.log. The handler should be configured for a maximum file size of 1 megabyte (1024*1024 bytes) and keep 5 backup log files.
    • Create and apply a custom log Formatter. The log message format must be exactly: %(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d].
    • Set the application logger's level to INFO.

Expected result

Your final code should be a complete, runnable Flask application that fulfills all the requirements. Specifically, it must contain:

  1. A logging configuration block that correctly creates and configures a RotatingFileHandler and a Formatter with the specified parameters ('app.log', maxBytes=1024*1024, backupCount=5, and the exact format string). The handler and log level must be correctly added to app.logger.
  2. A function decorated with @app.route('/') that returns the specified welcome string.
  3. A function decorated with @app.route('/crash') that contains the code 1 / 0.
  4. An error handler function decorated with @app.errorhandler(404). This function must accept an error argument and return the result of render_template_string(NOT_FOUND_TEMPLATE), along with the integer status code 404.
  5. A global error handler function decorated with @app.errorhandler(Exception). This function must accept an error argument. Inside, it must call app.logger.error() with exc_info=True to log the exception, and then return the result of render_template_string(INTERNAL_ERROR_TEMPLATE) along with the integer status code 500.
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.