0
0
Flaskframework~5 mins

Logging in production in Flask

Choose your learning style9 modes available
Introduction

Logging in production helps you keep track of what your app is doing and find problems quickly.

You want to see errors happening in your live Flask app.
You need to monitor app behavior without stopping it.
You want to keep a record of important events for later review.
You want to debug issues reported by users after deployment.
Syntax
Flask
import logging
from flask import Flask

app = Flask(__name__)

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

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

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

logging.basicConfig sets up the log file, level, and message format.

Use app.logger.info() or app.logger.error() to write logs.

Examples
This sets the log to only record errors and above, ignoring info messages.
Flask
logging.basicConfig(filename='app.log', level=logging.ERROR)
Logs a warning message that can help spot potential issues.
Flask
app.logger.warning('This is a warning message')
Changes the log message format to show only level and message.
Flask
logging.basicConfig(format='%(levelname)s:%(message)s')
Sample Program

This Flask app logs every visit to the index page into a file named production.log with timestamps and log levels.

Flask
import logging
from flask import Flask

app = Flask(__name__)

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

@app.route('/')
def index():
    app.logger.info('Index page visited')
    return 'Welcome to the production app!'

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

Logs are saved in the file specified by filename. Make sure your app has write permission.

Set the log level to INFO or ERROR depending on how much detail you want.

Use timestamps in logs to know when events happened.

Summary

Logging helps track app activity and errors in production.

Use logging.basicConfig to set up log files and levels.

Write logs with app.logger inside your Flask routes.