Send logs to logz.io from your Flask application
Logging is of great importance for web applications, both while in your local environment and for production applications. Logs can be analyzed and reveal issues and the can be used to debug applications.
In this post, we’ll see how to easily send logs from a flask application to logz.io. Logz.io has a quite generous free tier (1GB daily data volume), so feel free to register for a free account and run the code of this post for your own account.
So, let’s build our flask application first. We start by installing the dependencies:
Now, lets build our sample application:
So, in the code above, we create a mini application with just one endpoint. Within the route’s code, we log a warning message. The second file (config) holds the configuration of the application.
This file includes only our logz.io specific configuration, but in a real-world application it will probably have a lot more attributes. Config reads its values from environment variables. So, in order to fill Config’s attributes, we’ll need a .env file like this:
Ok! We now have our simple flask app and we want to send its logs to logz.io, too. The great news is that logz.io provides a logging handler for this purpose. We can add this handler in the application logger or in the root logger (in order to send all loggers’ messages to logz.io) and we’re done!
First, let’s install the new dependency:
Then, we can create a simple flask extension to use with our app:
This simple extension reads the token and logz.io endpoint/url from the application’s configuration, creates the handler that comes with the newly added dependency and we add the handler to the root logger. If you want to send only logs that you create via the application logger, the handler can be attached to app.logger
instead. Adding it to the root logger, will send all your logs to logz.io (e.g. sqlalchemy, application and any other library’s logs).
Now, the only thing remaining is to add the extension to our app:
That’s it! Now, all your logs will end up in logz.io, too. An important note about the configuration values needed for logz.io: you can get the token from the logz.io dashboard under Settings > General (section Account settings -> token) and use it as the value of LOGZIO_TOKEN
. Depending on the aws region you selected for storing your data, you may need to set the LOGZIO_URL
environment variable. Find out the different values for the url on this page.
That’s it for now!