Just Learn Code

Mastering Error Handling in Flask: Best Practices and Techniques

Error Handling in Flask:

Logging Errors

As developers, it is essential to monitor our application for errors or bugs constantly. Flask is a web framework that is primarily written in Python and used for developing web applications, among other things.

Flask offers multiple ways to handle errors, but one of the best ways is by logging them. In this article, we will discuss how to log errors in Flask, mainly focusing on the enabling and logging features.

Enabling Logging Feature in Flask:

When building your Flask app, it is crucial to note that you should not use the debug mode in production. Instead, you should use the Flask app “logging module.” The logging module is a way to log errors and allow you to get more specific details on what is happening in your application.

Enabling the logging feature in Flask is as easy as including these lines of code in your app:

“` python

import logging

from logging.handlers import RotatingFileHandler

if not app.debug:

# This code sets up the logging configuration

logging.basicConfig(filename=’myapp.log’, level=logging.DEBUG)


If your app is not in debug mode, the code creates a file named “myapp.log,” which is where logs will be stored. In the above example, the logging level is set to logging.DEBUG, which means that it will log debug, info, warning, error, and critical severity levels.

Logging Errors:

Now that we have enabled the logging feature, we can begin logging errors. Flask provides a built-in logger named “app.logger,” which is what we will use to log errors.

“` python


#code block

except Exception as e:

app.logger.error(“Error occurred: ” + str(e))


Here, if an exception occurs, it is caught in the try/except block, and the error message is logged via Flask’s built-in logger. The `app.logger.error()` method logs an error message with severity level ERROR.

Creating Error Log File:

It is vital to have a separate file to store all of our error logs. This file can be used to track down the HTTP errors or application errors that we might encounter while the application is in use.

To create an error log file, we can make use of the RotatingFileHandler object available in the logging module in Flask. “` python

import logging

from logging.handlers import RotatingFileHandler

if not app.debug:

# This code sets up the logging configuration

handler = RotatingFileHandler(‘errorlogs.txt’, maxBytes=10000, backupCount=1)




The code above sets up a rotating file handler that will log events of a severity of WARNING or higher to an `errorlogs.txt` file, which, when it exceeds 10KB, is then rotated, and the logger will use the newly created file to log the errors. Conclusion:

As software developers, we must monitor our applications for errors and bugs constantly.

Flask is a useful tool to help us build seamless web applications. It is essential to use the proper error handling techniques to provide a better user experience.

In this article, we have discussed how to log errors in Flask and how to enable Flask’s in-built logging feature to store logs. By following the steps mentioned above, you can keep track of all the errors that occur in your Flask application and take the necessary steps to debug and fix them.

3) Example Implementation and Output:

In this section, we will show an example of how to implement error logging in a Flask application. We will also show you what happens when an error occurs, how to return the error and where to look for log details.

Returning Error in Flask App:

To demonstrate error logging in Flask, we will create a simple application that raises an error. We have created a function that tries to divide 1 by 0, which results in an error.

Here is the code:

“` python

from flask import Flask

app = Flask(__name__)


def index():


return str(1/0)

except ZeroDivisionError as e:


return “Fail”


In the code above, when the `index` endpoint is called, it will try to divide 1 by 0, which is impossible. Thus, it will raise a `ZeroDivisionError` exception, and the code inside the `except` block will run.

Here, we are logging the error using Flask’s built-in logger, and we are also returning the string “Fail” to indicate that something went wrong. Internal Server Error and Error Log Details:

Now, let’s run the application to see what happens when an error occurs.

When we go to `http://localhost:5000/` in our browser, we will see a message that says “Internal Server Error.” This error occurs since we tried to divide by 0, and Python cannot perform this operation. To see the error log details and why the error occurred, we need to look at the `errorlogs.txt` file that we created earlier.

In the log file, we will see the following details:


ERROR:root:division by zero

Traceback (most recent call last):

File “main.py”, line 9, in index

return str(1/0)

ZeroDivisionError: division by zero


From the log details, we can see that the error occurred when trying to divide 1 by 0, and the severity level is ERROR. 4) Further Resources:

Flask has an excellent official documentation that covers error handling in more detail.

The documentation provides a list of other handlers that can be used for error logging, such as:

– SMTPHandler: Sends an email to a specified recipient. – SysLogHandler: Sends error messages to the system log.

– HTTPHandler: Sends error messages to a specified HTTP server. Exploring Other Handlers for Error Logging:

To explore other handlers for error logging, let’s modify our code to use the SMTPHandler.

We will set it up to send an email to our email address when an error occurs. Here is the code:

“` python

from logging.handlers import SMTPHandler

if not app.debug:

# This sets up the SMTPHandler to send us an email when an error occurs.

mail_handler = SMTPHandler(


fromaddr=’[email protected]’,


subject=’Flask Application Error’,

credentials=(’email_account’, ‘password’),






In the code above, we are setting up the `SMTPHandler` to send an email to our Gmail account when an error occurs. We will need to replace `[email protected]`, `email_address`, `email_account`, and `password` with our appropriate values.

Also, notice that `secure=()` is an empty tuple since we are using Gmail, and we do not need to specify any security protocol. Finally, we set the log level to `logging.ERROR` to send emails only when an error with severity level ERROR occurs.

With the SMTPHandler set up, whenever an error occurs in the application, Flask sends an email to our specified email address. This way, we can stay informed of any errors that occur in our application without the need to check the log file manually.


In this article, we covered how to log errors in a Flask application using Flask’s built-in logger and enabling Flask’s logging feature. We demonstrated how to catch and log errors using a simple Flask application, and we also demonstrated how to view our error logs and their details.

We also showed how other handlers, such as SMTPHandler, can be used to send emails when an error occurs. Moreover, we showed how Flask’s official documentation could be used to explore other handlers for error logging.

In this article, we learned how to implement error logging in Flask, focusing on enabling and logging features. We explored the importance of monitoring applications for errors and the significance of error handling techniques to provide a better user experience.

We covered how to log errors and catch them by using a few lines of code in a Flask application. We explored the various logging levels available and highlighted how to use Flask’s inbuilt logger to store logs in a separate file.

Additionally, we demonstrated how to use other handlers, such as SMTPHandler, for error logging. The article concludes by emphasizing the significance of error logging in Flask to monitor applications for errors and concluded that developers should take error logging seriously for optimal web application development.

Popular Posts