How to Log Errors in Flask: Simple Guide with Examples
In Flask, you can log errors by using Python's built-in
logging module and configuring it in your app. You can also use Flask's errorhandler decorator to catch errors and log them for easier debugging and monitoring.Syntax
To log errors in Flask, you typically use Python's logging module. You set up a logger, configure its level, and specify where to send logs (console, file, etc.). Flask's @app.errorhandler decorator lets you catch specific HTTP errors or exceptions and log them.
logging.getLogger(): Gets the logger instance.logger.error(): Logs an error message.@app.errorhandler(): Decorator to handle errors.
python
import logging from flask import Flask, request app = Flask(__name__) # Set up logger logger = logging.getLogger(__name__) logger.setLevel(logging.ERROR) @app.errorhandler(500) def internal_error(error): logger.error(f"Server Error: {error}, Path: {request.path}") return "Internal Server Error", 500
Example
This example shows how to configure logging to a file and log errors when a server error occurs. It demonstrates catching a 500 error and logging details including the error message and request path.
python
import logging from flask import Flask, request app = Flask(__name__) # Configure logging to a file logging.basicConfig(filename='error.log', level=logging.ERROR, format='%(asctime)s %(levelname)s: %(message)s') @app.route('/') def index(): # This will cause a ZeroDivisionError 1 / 0 return "Hello" @app.errorhandler(500) def internal_error(error): logging.error(f"Error: {error}, Path: {request.path}") return "Internal Server Error", 500 if __name__ == '__main__': app.run(debug=False)
Output
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [date time] "GET / HTTP/1.1" 500 -
Common Pitfalls
Common mistakes when logging errors in Flask include:
- Not configuring the logger properly, so logs don't appear.
- Using
debug=Truein production, which can hide error logging. - Logging inside the error handler without enough context.
- Not handling exceptions globally, missing some errors.
Always configure logging before running the app and test error handlers.
python
import logging from flask import Flask app = Flask(__name__) # Wrong: No logging configuration, logs may not show logger = logging.getLogger(__name__) @app.route('/') def index(): 1 / 0 @app.errorhandler(500) def internal_error(error): # Wrong: Using print instead of logging print(f"Error occurred: {error}") return "Error", 500 # Correct way: logging.basicConfig(level=logging.ERROR) @app.errorhandler(500) def internal_error_correct(error): logging.error(f"Error: {error}") return "Error", 500
Quick Reference
Tips for logging errors in Flask:
- Use
logging.basicConfig()to set log level and output. - Use
@app.errorhandler()to catch and log errors. - Log useful info like error message and request path.
- Test error logging by forcing errors during development.
- Disable
debug=Truein production for proper logging.
Key Takeaways
Use Python's logging module configured with basicConfig for error logging in Flask.
Handle errors with @app.errorhandler to log exceptions and return responses.
Always log useful context like error details and request path for easier debugging.
Avoid using debug mode in production to ensure errors are properly logged.
Test your error logging setup by triggering errors during development.