OpenTelemetry Flask Instrumentation

This library builds on the OpenTelemetry WSGI middleware to track web requests in Flask applications. In addition to opentelemetry-util-http, it supports Flask-specific features such as:

  • The Flask url rule pattern is used as the Span name.

  • The http.route Span attribute is set so that one can see which URL rule matched a request.

Usage

from flask import Flask
from opentelemetry.instrumentation.flask import FlaskInstrumentor

app = Flask(__name__)

FlaskInstrumentor().instrument_app(app)

@app.route("/")
def hello():
    return "Hello!"

if __name__ == "__main__":
    app.run(debug=True)

Configuration

Exclude lists

To exclude certain URLs from tracking, set the environment variable OTEL_PYTHON_FLASK_EXCLUDED_URLS (or OTEL_PYTHON_EXCLUDED_URLS to cover all instrumentations) to a string of comma delimited regexes that match the URLs.

For example,

export OTEL_PYTHON_FLASK_EXCLUDED_URLS="client/.*/info,healthcheck"

will exclude requests such as https://site/client/123/info and https://site/xyz/healthcheck.

You can also pass comma delimited regexes directly to the instrument_app method:

FlaskInstrumentor().instrument_app(app, excluded_urls="client/.*/info,healthcheck")

Request/Response hooks

This instrumentation supports request and response hooks. These are functions that get called right after a span is created for a request and right before the span is finished for the response.

  • The client request hook is called with the internal span and an instance of WSGIEnvironment (flask.request.environ) when the method receive is called.

  • The client response hook is called with the internal span, the status of the response and a list of key-value (tuples) representing the response headers returned from the response when the method send is called.

For example,

from opentelemetry.trace import Span
from wsgiref.types import WSGIEnvironment
from typing import List

from opentelemetry.instrumentation.flask import FlaskInstrumentor

def request_hook(span: Span, environ: WSGIEnvironment):
    if span and span.is_recording():
        span.set_attribute("custom_user_attribute_from_request_hook", "some-value")

def response_hook(span: Span, status: str, response_headers: List):
    if span and span.is_recording():
        span.set_attribute("custom_user_attribute_from_response_hook", "some-value")

FlaskInstrumentor().instrument(request_hook=request_hook, response_hook=response_hook)

Flask Request object reference: https://flask.palletsprojects.com/en/2.1.x/api/#flask.Request

Capture HTTP request and response headers

You can configure the agent to capture specified HTTP headers as span attributes, according to the semantic conventions.

Request headers

To capture HTTP request headers as span attributes, set the environment variable OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST to a comma delimited list of HTTP header names.

For example,

export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="content-type,custom_request_header"

will extract content-type and custom_request_header from the request headers and add them as span attributes.

Request header names in Flask are case-insensitive and - characters are replaced by _. So, giving the header name as CUStom_Header in the environment variable will capture the header named custom-header.

Regular expressions may also be used to match multiple headers that correspond to the given pattern. For example:

export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="Accept.*,X-.*"

Would match all request headers that start with Accept and X-.

To capture all request headers, set OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST to ".*".

export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST=".*"

The name of the added span attribute will follow the format http.request.header.<header_name> where <header_name> is the normalized HTTP header name (lowercase, with - replaced by _). The value of the attribute will be a single item list containing all the header values.

For example: http.request.header.custom_request_header = ["<value1>,<value2>"]

Response headers

To capture HTTP response headers as span attributes, set the environment variable OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE to a comma delimited list of HTTP header names.

For example,

export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="content-type,custom_response_header"

will extract content-type and custom_response_header from the response headers and add them as span attributes.

Response header names in Flask are case-insensitive. So, giving the header name as CUStom-Header in the environment variable will capture the header named custom-header.

Regular expressions may also be used to match multiple headers that correspond to the given pattern. For example:

export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="Content.*,X-.*"

Would match all response headers that start with Content and X-.

To capture all response headers, set OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE to ".*".

export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE=".*"

The name of the added span attribute will follow the format http.response.header.<header_name> where <header_name> is the normalized HTTP header name (lowercase, with - replaced by _). The value of the attribute will be a single item list containing all the header values.

For example: http.response.header.custom_response_header = ["<value1>,<value2>"]

Sanitizing headers

In order to prevent storing sensitive data such as personally identifiable information (PII), session keys, passwords, etc, set the environment variable OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS to a comma delimited list of HTTP header names to be sanitized. Regexes may be used, and all header names will be matched in a case-insensitive manner.

For example,

export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS=".*session.*,set-cookie"

will replace the value of headers such as session-id and set-cookie with [REDACTED] in the span.

Note

The environment variable names used to capture HTTP headers are still experimental, and thus are subject to change.

SQLCommenter

You can optionally enable sqlcommenter which enriches the query with contextual information. Queries made after setting up trace integration with sqlcommenter enabled will have configurable key-value pairs appended to them, e.g. "select * from auth_users; /*framework=flask%%3A2.9.3*/". This supports context propagation between database client and server when database log records are enabled. For more information, see:

from opentelemetry.instrumentation.flask import FlaskInstrumentor

FlaskInstrumentor().instrument(enable_commenter=True)

Note

FlaskInstrumentor sqlcommenter requires that sqlcommenter is also enabled for an active instrumentation of a database driver or object-relational mapper (ORM) in the same database client stack. The latter, such as Psycopg2Instrumentor of SQLAlchemyInstrumentor, will create a base sqlcomment that is enhanced by FlaskInstrumentor with additional values from context before appending to the query statement.

SQLCommenter with commenter_options

The key-value pairs appended to the query can be configured using commenter_options. When sqlcommenter is enabled, all available KVs/tags are calculated by default. commenter_options supports opting out of specific KVs.

from opentelemetry.instrumentation.flask import FlaskInstrumentor

# Opts into sqlcomment for Flask trace integration.
# Opts out of tags for controller.
FlaskInstrumentor().instrument(
    enable_commenter=True,
    commenter_options={
        "controller": False,
    }
)

Available commenter_options

The following sqlcomment key-values can be opted out of through commenter_options:

Commenter Option

Description

Example

framework

Flask framework name with version (URL encoded).

framework='flask%%%%3A2.9.3'

route

Flask route URI pattern.

route='/home'

controller

Flask controller/endpoint name.

controller='home_view'

API

opentelemetry.instrumentation.flask.get_default_span_name()[source]
class opentelemetry.instrumentation.flask.FlaskInstrumentor(*args, **kwargs)[source]

Bases: BaseInstrumentor

An instrumentor for flask.Flask

See BaseInstrumentor

instrumentation_dependencies()[source]

Return a list of python packages with versions that the will be instrumented.

The format should be the same as used in requirements.txt or pyproject.toml.

For example, if an instrumentation instruments requests 1.x, this method should look like: :rtype: Collection[str]

def instrumentation_dependencies(self) -> Collection[str]:

return [‘requests ~= 1.0’]

This will ensure that the instrumentation will only be used when the specified library is present in the environment.

static instrument_app(app, request_hook=None, response_hook=None, tracer_provider=None, excluded_urls=None, enable_commenter=True, commenter_options=None, meter_provider=None)[source]
static uninstrument_app(app)[source]