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 being tracked, set the environment variable OTEL_PYTHON_FLASK_EXCLUDED_URLS (or OTEL_PYTHON_EXCLUDED_URLS as fallback) with comma delimited regexes representing which URLs to exclude.

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 the comma delimited regexes to the instrument_app method directly:

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

Request/Response hooks

Utilize request/reponse hooks to execute custom logic to be performed before/after performing a request. Environ is an instance of WSGIEnvironment (flask.request.environ). Response_headers is a list of key-value (tuples) representing the response headers returned from the response.

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")

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

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

Capture HTTP request and response headers

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

Request headers

To capture predefined HTTP request headers as span attributes, set the environment variable OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST to a comma-separated 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 request headers and add them as span attributes.

It is recommended that you should give the correct names of the headers to be captured in the environment variable. Request header names in flask are case insensitive and - characters are replaced by _. So, giving header name as CUStom_Header in environment variable will be able capture header with name custom-header.

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

Example of the added span attribute, http.request.header.custom_request_header = ["<value1>,<value2>"]

Response headers

To capture predefined HTTP response headers as span attributes, set the environment variable OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE to a comma-separated 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 response headers and add them as span attributes.

It is recommended that you should give the correct names of the headers to be captured in the environment variable. Response header names captured in flask are case insensitive. So, giving header name as CUStomHeader in environment variable will be able capture header with name customheader.

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

Example of the added span attribute, http.response.header.custom_response_header = ["<value1>,<value2>"]

Note

Environment variable names to capture http headers are still experimental, and thus are subject to change.

API

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

Bases: opentelemetry.instrumentation.instrumentor.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 setup.py.

For example, if an instrumentation instruments requests 1.x, this method should look like:

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.

Return type

Collection[str]

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