OpenTelemetry WSGI Instrumentation
This library provides a WSGI middleware that can be used on any WSGI framework (such as Django, Flask, or Web.py) to track requests timing through OpenTelemetry. It is part of the `opentelemetry-python-contrib` repository and is released frequently alongside the main OpenTelemetry Python SDK, often in beta versions.
Warnings
- breaking In earlier versions (e.g., prior to `0.30b0`), `opentelemetry-instrumentation-wsgi` added `http.method` to the `span.name`. If your observability dashboards or alerts rely on a specific span name format from older versions, this change might break them.
- gotcha Capturing custom HTTP request and response headers requires setting specific environment variables (e.g., `OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST` and `OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`). For request headers, names are case-insensitive and hyphens (`-`) are replaced by underscores (`_`) when setting the environment variable (e.g., `Custom-Header` becomes `CUStom_Header`). For response headers, names are case-insensitive.
- gotcha As indicated by the `0.x.y.bZ` versioning (e.g., `0.61b0`), this library is currently in beta. This means that its API and behavior might not be fully stable and could be subject to breaking changes in future releases without a major version bump.
- gotcha The `opentelemetry-instrumentation-wsgi` package provides middleware, but it does not automatically configure the OpenTelemetry SDK (TracerProvider, SpanProcessor, Exporter). You must manually configure the OpenTelemetry SDK in your application's entry point for traces to be collected and exported.
Install
-
pip install opentelemetry-instrumentation-wsgi opentelemetry-sdk opentelemetry-exporter-otlp
Imports
- OpenTelemetryMiddleware
from opentelemetry.instrumentation.wsgi import OpenTelemetryMiddleware
Quickstart
import os
from flask import Flask
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
from opentelemetry.instrumentation.wsgi import OpenTelemetryMiddleware
# Configure OpenTelemetry SDK
resource = Resource.create({"service.name": os.environ.get('OTEL_SERVICE_NAME', 'my-wsgi-app')})
tracer_provider = TracerProvider(resource=resource)
span_processor = SimpleSpanProcessor(ConsoleSpanExporter())
tracer_provider.add_span_processor(span_processor)
trace.set_tracer_provider(tracer_provider)
# Your WSGI application (example using Flask)
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello, world!"
# Wrap your WSGI application with the OpenTelemetry middleware
app.wsgi_app = OpenTelemetryMiddleware(app.wsgi_app)
if __name__ == "__main__":
# Run with a production WSGI server like Gunicorn in a real scenario
# For this example, running Flask's development server directly
app.run(debug=True)