OpenTelemetry WSGI Instrumentation

0.61b0 · active · verified Sun Mar 29

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

Install

Imports

Quickstart

This example demonstrates how to set up basic OpenTelemetry tracing for a Flask application using the `opentelemetry-instrumentation-wsgi` middleware. It configures a `TracerProvider` with a `ConsoleSpanExporter` to print traces to the console, then wraps the Flask app's WSGI application with `OpenTelemetryMiddleware`.

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)

view raw JSON →