BudiBadu Logo
Samplebadu

Flask by Example: Logging Configuration Setup

Flask 3.0+

Proper logging is vital for debugging and monitoring. This sample shows how to configure Flask's built-in logger to output messages to both the console and a file.

Code

import logging
from logging.handlers import RotatingFileHandler
from flask import Flask

app = Flask(__name__)

# 1. Configure the Logger
if not app.debug:
    # Create a file handler
    file_handler = RotatingFileHandler(
        'app.log', 
        maxBytes=10240, 
        backupCount=10
    )
    
    # Set the format
    file_handler.setFormatter(logging.Formatter(
        '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
    ))
    
    # Set the level
    file_handler.setLevel(logging.INFO)
    
    # Add handler to Flask's logger
    app.logger.addHandler(file_handler)
    app.logger.setLevel(logging.INFO)
    app.logger.info('Application startup')

@app.route('/')
def index():
    # 2. Log messages
    app.logger.info('Index page accessed')
    try:
        1 / 0
    except ZeroDivisionError:
        app.logger.error('An error occurred', exc_info=True)
    return "Check the logs!"

Explanation

Flask uses the standard Python logging library, providing a pre-configured logger accessible via app.logger. In production, you typically want to log to a file rather than just standard output, so you can review events later. Using a RotatingFileHandler is a best practice as it prevents the log file from growing indefinitely by creating new files after a certain size limit is reached.

You can customize the format of your log messages to include timestamps, log levels (INFO, ERROR, etc.), and the location in the code where the log was generated. This context is invaluable when trying to trace the source of a bug or understand the sequence of events that led to an error.

It is common to configure logging conditionally based on the environment. For example, you might want verbose logging to the console during development (debug mode), but structured logging to a file or an external aggregation service when running in production. This setup ensures you have the right visibility without cluttering your development output.

Code Breakdown

10
RotatingFileHandler manages log files. maxBytes=10240 limits the file size to 10KB, and backupCount=10 keeps the last 10 log files.
17
setFormatter defines the layout. %(asctime)s adds the time, and %(pathname)s:%(lineno)d adds the file path and line number.
37
exc_info=True includes the full stack trace in the log output. This is critical when logging exceptions inside an except block.