Monitor Flask performance with OpenTelemetry

Flask is a small and lightweight Python web framework that provides useful tools and features that make creating web applications in Python easier

In this article you will learn how to monitor and optimize Flask performance using OpenTelemetry observability framework.

What is OpenTelemetry?

OpenTelemetry is a vendor-neutral standard on how to collect telemetry data for applications and their supporting infrastructures. OpenTelemetry was created via the merger of OpenCensus and OpenTracing projects.

OpenTelemetry aims to standardize how you collect and send telemetry data to backend platforms: tracesopen in new window, metricsopen in new window, and logsopen in new window.

Installation

To instrument a Flask app, you need to install a correspoding Flask OpenTelemetry instrumentation:

pip install opentelemetry-instrumentation-flask

Usage

Then you can instrument the Flask app:

from opentelemetry.instrumentation.flask import FlaskInstrumentor

app = Flask(__name__)
FlaskInstrumentor().instrument_app(app)

See exampleopen in new window from details.

Instrumenting SQLAlchemy

To instrument SQLAlchemy database client, you need to install a corresponding SQLAlchemy instrumentation:

pip install opentelemetry-instrumentation-sqlalchemy

Then instrument the db engine:

from flask_sqlalchemy import SQLAlchemy
from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor

app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:"
db = SQLAlchemy(app)
SQLAlchemyInstrumentor().instrument(engine=db.engine)

See Instrumenting SQLAlchemy with OpenTelemetry for details.

What is Uptrace?

Once your app is instrumented, you need a backend platform to store observability data collected by OpenTelemetry.

Uptrace is an open source APM for OpenTelemetry that helps developers pinpoint failures and find performance bottlenecks. Uptrace can process billions of spans on a single server and allows to monitor your software at 10x lower cost.

You can get startedopen in new window with Uptrace by downloading a DEB/RPM package or a pre-compiled Go binary.

What's next?

Next, instrument more operations, for example, database queries and network calls. You can also learn about OpenTelemetry Python Tracing API to create your own instrumentations.

More examples:

See also:

Last Updated: