Writing error log is one of the crucial things when writing a web applications. It’s really helpful when trying to debug where things went wrong. In this tutorial, we’ll have a look at how to write error log in Python Flask web application.
We’ll start by creating a simple web application using Python Flask. Create a project LogApp and a file called app.py.
mkdir LogApp cd LogApp vim app.py
Add the following code to app.py.
from flask import Flask app = Flask(__name__) @app.route("/log") def logTest(): return "Code Handbook !! Log testing." if __name__ == "__main__": app.run()
Writing Error Log in Python Flask
To get started with logging error and other information, all you need to do is import the logging library from python. Once the library has been imported, we’ll be using the RotatingFileHandler handler to handler logging.
import logging from logging.handlers import RotatingFileHandler
Initialize the log handler when the application in initiated. Set the logging levels to ERROR, INFO or WARNING. Important point to note here is to set both the app.logger level and the RotatingFileHandler level.
if __name__ == "__main__": # initialize the log handler logHandler = RotatingFileHandler('info.log', maxBytes=1000, backupCount=1) # set the log handler level logHandler.setLevel(logging.INFO) # set the app logger level app.logger.setLevel(logging.INFO) app.logger.addHandler(logHandler) app.run()
Try adding some different level logs to the /log handler and it should be written to the info.log file in the logApp project folder.
@app.route("/log") def logTest(): app.logger.warning('testing warning log') app.logger.error('testing error log') app.logger.info('testing info log') return "Code Handbook !! Log testing."
Wrapping It Up
In this tutorial, we saw how to handle error log in Python Flask web application. We used logging python library to write logs in our Flask application. The handler used is RotatingFileHandler which rotates the log file when the size of the file exceeds a certain limit.
Have you faced any other issues while trying to write logs in a Python Flask web application ? Do let us know your thoughts in the comments below.