8. Stream and File Logging Handler attached to Flask

Logging is a critical component of any web application, including those built with Flask. Proper logging allows you to track the application's activity, debug issues, and maintain records of different events. In Flask, you can set up both stream and file logging handlers to capture and store log information.

Stream and File Logging in Flask

  1. Stream Logging: This type of logging sends log messages to a stream, such as the console or standard output. It's useful for real-time monitoring and debugging.

  2. File Logging: This type of logging writes log messages to a file. It's useful for persistent log records, which can be analyzed later.

Setting Up Logging in Flask

Here's an example of how to set up both stream and file logging handlers in a Flask application:

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

app = Flask(__name__)

# Configure stream handler for console output
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)
stream_handler.setFormatter(logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
))

# Configure file handler for file output
file_handler = RotatingFileHandler('app.log', maxBytes=10000, backupCount=3)
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
))

# Add handlers to the Flask app's logger
app.logger.addHandler(stream_handler)
app.logger.addHandler(file_handler)

@app.route('/')
def hello():
    app.logger.info('Hello endpoint was reached')
    return 'Hello, World!'

@app.route('/error')
def error():
    try:
        1 / 0
    except Exception as e:
        app.logger.error('An error occurred: %s', e)
    return 'An error occurred, check logs for details.'

if __name__ == '__main__':
    app.run(debug=True)

Explanation

  • Import Statements: The necessary modules for logging are imported. logging is Python's standard logging library, and RotatingFileHandler is used for log file rotation.

  • Stream Handler:

    • StreamHandler() creates a handler that logs to the console.

    • setLevel(logging.INFO) sets the logging level to INFO.

    • setFormatter(logging.Formatter(...)) sets the format for log messages.

  • File Handler:

    • RotatingFileHandler('app.log', maxBytes=10000, backupCount=3) creates a file handler that writes log messages to app.log, rotating the log file after it reaches 10,000 bytes, keeping up to 3 backup files.

    • setLevel(logging.INFO) and setFormatter(...) are similar to the stream handler.

  • Adding Handlers to Logger: Both handlers are added to the Flask app's logger with app.logger.addHandler(...).

  • Logging in Routes:

    • app.logger.info('Hello endpoint was reached') logs an INFO message when the root endpoint is reached.

    • In the /error route, app.logger.error('An error occurred: %s', e) logs an ERROR message if an exception occurs.

Running the Application

  • When the application runs and the root endpoint is accessed, an INFO log message will be printed to the console and written to app.log.

  • If the /error endpoint is accessed and an exception occurs, an ERROR log message will be similarly recorded.

Benefits

  • Stream Logging: Helps in real-time debugging and monitoring of the application while it's running.

  • File Logging: Provides a persistent record of events, useful for post-mortem analysis and long-term monitoring.

This setup ensures that you have both real-time visibility and historical records of your application's behavior, which is essential for effective monitoring and troubleshooting.

Last updated