Flask OpenTracing

2.0.0 · active · verified Fri Apr 17

Flask-opentracing provides OpenTracing support for Flask applications. It enables automatic and manual tracing of requests, integrating with OpenTracing-compatible tracers like Jaeger or Zipkin. The library is currently at version 2.0.0 and maintains an active release cadence aligned with OpenTracing API updates.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart initializes a Flask application with `FlaskTracing`, using a `MockTracer` for demonstration. It configures `trace_all_requests=True` to automatically trace all incoming HTTP requests. Custom spans and tags can be added within routes by retrieving the current span using `tracing.get_span()`.

from flask import Flask
from flask_opentracing import FlaskTracing
from opentracing.mocktracer import MockTracer

app = Flask(__name__)

# Initialize FlaskTracing with an OpenTracing-compatible tracer.
# For production, replace MockTracer with a real tracer like Jaeger or Zipkin.
# e.g., from jaeger_client import Config; tracer = Config(service_name='my-app').initialize_tracer()
# Use os.environ.get for dynamic configuration if needed.
tracing = FlaskTracing(MockTracer(), app=app, trace_all_requests=True)

@app.route('/')
def hello():
    # Get the current active span for manual instrumentation
    span = tracing.get_span()
    if span:
        span.set_tag('hello-to', 'world')
    return "Hello World!"

@app.route('/greet/<name>')
def greet(name):
    span = tracing.get_span()
    if span:
        span.set_tag('greeting-name', name)
    return f"Hello, {name}!"

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

view raw JSON →