OpenTelemetry WSGI Instrumentation

This library provides a WSGI middleware that can be used on any WSGI framework (such as Django / Flask) to track requests timing through OpenTelemetry.

Usage (Flask)

from flask import Flask
from opentelemetry.instrumentation.wsgi import OpenTelemetryMiddleware

app = Flask(__name__)
app.wsgi_app = OpenTelemetryMiddleware(app.wsgi_app)

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

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

Usage (Django)

Modify the application’s wsgi.py file as shown below.

import os
from opentelemetry.instrumentation.wsgi import OpenTelemetryMiddleware
from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'application.settings')

application = get_wsgi_application()
application = OpenTelemetryMiddleware(application)

API

class opentelemetry.instrumentation.wsgi.CarrierGetter[source]

Bases: opentelemetry.trace.propagation.textmap.DictGetter

get(carrier, key)[source]
Getter implementation to retrieve a HTTP header value from the

PEP3333-conforming WSGI environ

Parameters
  • carrier (dict) – WSGI environ object

  • key (str) – header name in environ object

Return type

List[str]

Returns

A list with a single string with the header value if it exists, else an empty list.

keys(carrier)[source]

Function that can retrieve all the keys in a carrier object.

Parameters

carrier – An object which contains values that are used to construct a Context.

Returns

list of keys from the carrier.

opentelemetry.instrumentation.wsgi.setifnotnone(dic, key, value)[source]
opentelemetry.instrumentation.wsgi.collect_request_attributes(environ)[source]

Collects HTTP request attributes from the PEP3333-conforming WSGI environ and returns a dictionary to be used as span creation attributes.

opentelemetry.instrumentation.wsgi.add_response_attributes(span, start_response_status, response_headers)[source]

Adds HTTP response attributes to span using the arguments passed to a PEP3333-conforming start_response callable.

opentelemetry.instrumentation.wsgi.get_default_span_name(environ)[source]

Default implementation for name_callback, returns HTTP {METHOD_NAME}.

class opentelemetry.instrumentation.wsgi.OpenTelemetryMiddleware(wsgi, name_callback=<function get_default_span_name>)[source]

Bases: object

The WSGI application middleware.

This class is a PEP 3333 conforming WSGI middleware that starts and annotates spans for any requests it is invoked with.

Parameters
  • wsgi – The WSGI application callable to forward requests to.

  • name_callback – Callback which calculates a generic span name for an incoming HTTP request based on the PEP3333 WSGI environ. Optional: Defaults to get_default_span_name.