OpenTelemetry WSGI Instrumentation

This library provides a WSGI middleware that can be used on any WSGI framework (such as Django / Flask / Web.py) 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)

Usage (Web.py)

import web
from opentelemetry.instrumentation.wsgi import OpenTelemetryMiddleware
from cheroot import wsgi

urls = ('/', 'index')


class index:

    def GET(self):
        return "Hello, world!"


if __name__ == "__main__":
    app = web.application(urls, globals())
    func = app.wsgifunc()

    func = OpenTelemetryMiddleware(func)

    server = wsgi.WSGIServer(
        ("localhost", 5100), func, server_name="localhost"
    )
    server.start()

Configuration

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 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,

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, environ: WSGIEnvironment, status: str, response_headers: List):
    if span and span.is_recording():
        span.set_attribute("custom_user_attribute_from_response_hook", "some-value")

OpenTelemetryMiddleware(request_hook=request_hook, response_hook=response_hook)

Capture HTTP request and response headers

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

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 WSGI 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 WSGI 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.

API

class opentelemetry.instrumentation.wsgi.WSGIGetter(*args, **kwds)[source]

Bases: opentelemetry.propagators.textmap.Getter[dict]

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

    Returns:

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

Return type

Optional[List[str]]

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.collect_custom_request_headers_attributes(environ)[source]

Returns custom HTTP request headers which are configured by the user from the PEP3333-conforming WSGI environ to be used as span creation attributes as described in the specification https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers

opentelemetry.instrumentation.wsgi.collect_custom_response_headers_attributes(response_headers)[source]

Returns custom HTTP response headers which are configured by the user from the PEP3333-conforming WSGI environ as described in the specification https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers

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, request_hook=None, response_hook=None, tracer_provider=None, meter_provider=None)[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.

  • request_hook – Optional callback which is called with the server span and WSGI environ object for every incoming request.

  • response_hook – Optional callback which is called with the server span, WSGI environ, status_code and response_headers for every incoming request.

  • tracer_provider – Optional tracer provider to use. If omitted the current globally configured one is used.

class opentelemetry.instrumentation.wsgi.ResponsePropagationSetter[source]

Bases: object

set(carrier, key, value)[source]