0
0
Flaskframework~5 mins

Logging configuration in Flask

Choose your learning style9 modes available
Introduction

Logging helps you keep track of what your Flask app is doing. It records important events and errors so you can understand and fix problems.

You want to see errors when your Flask app crashes.
You want to record user actions for debugging.
You want to monitor app behavior in production.
You want to save logs to a file for later review.
You want to control the detail level of messages shown.
Syntax
Flask
import logging
from flask import Flask

app = Flask(__name__)

logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s: %(message)s')

@app.route('/')
def home():
    app.logger.info('Home page accessed')
    return 'Hello, Flask!'

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

logging.basicConfig sets up the logging system with level and format.

app.logger is Flask's built-in logger to write messages.

Examples
Set logging to show all messages from DEBUG level and above.
Flask
logging.basicConfig(level=logging.DEBUG)
Save warning and error messages to a file named app.log.
Flask
logging.basicConfig(filename='app.log', level=logging.WARNING)
Log an error message using Flask's logger.
Flask
app.logger.error('An error happened!')
Sample Program

This Flask app logs an info message every time the home page is visited. The log shows the time, level, and message.

Flask
import logging
from flask import Flask

app = Flask(__name__)

logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s: %(message)s')

@app.route('/')
def home():
    app.logger.info('Home page accessed')
    return 'Hello, Flask!'

if __name__ == '__main__':
    app.run()
OutputSuccess
Important Notes

Use different logging levels: DEBUG, INFO, WARNING, ERROR, CRITICAL to control message importance.

Logging to a file helps keep records even after the app stops.

Flask's app.logger is ready to use and integrates with Python's logging module.

Summary

Logging records app events and errors to help debugging and monitoring.

Use logging.basicConfig to set up logging level and format.

Use app.logger in Flask to write log messages easily.