OpenTelemetry guide
OpenTelemetry for Flask
Flask is small, and so is its instrumentation. A few lines give you a span per route with the SQLAlchemy queries and outgoing HTTP calls nested inside.
3 min read11 sectionsUpdated
On this page
from flask import Flask
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.instrumentation.flask import FlaskInstrumentor
from opentelemetry.instrumentation.requests import RequestsInstrumentor
from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from .db import engine
provider = TracerProvider(resource=Resource.create({"service.name": "catalog", "deployment.environment.name": "production"}))
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(endpoint="http://localhost:4318/v1/traces")))
trace.set_tracer_provider(provider)
app = Flask(__name__)
FlaskInstrumentor().instrument_app(app, excluded_urls="health,metrics")
SQLAlchemyInstrumentor().instrument(engine=engine)
RequestsInstrumentor().instrument()
@app.get("/products/<int:product_id>")
def product(product_id):
...Or with zero code
If you prefer not to touch the app, install opentelemetry-distro, run opentelemetry-bootstrap -a install, and start with opentelemetry-instrument flask run (or your WSGI server command) with the same environment variables as in the Python guide. Do not combine both approaches in one process, or you get duplicate spans.
Route names, not URLs
The Flask instrumentation names server spans by the rule, such as GET /products/<int:product_id>, so all product pages group into one endpoint with meaningful p95 and error rate. If you build URLs dynamically outside Flask routing, check the endpoint list for high-cardinality names.
Send it to VitalRix
Shortcut. The VitalRix package does all of the above for you: pip install vitalrix, then vitalrix.init() before the app serves: it turns on every installed instrumentation and sends traces, metrics and logging records. It reads VITALRIX_URL, VITALRIX_API_KEY, OTEL_SERVICE_NAME and DEPLOYMENT_ENVIRONMENT.
Directly. VitalRix accepts OTLP over HTTP with protobuf or JSON, which is what the Python exporter sends. Instead of a Collector at localhost:4318, point the exporter at VitalRix with the per-signal endpoints and your API key. Create the key in VitalRix under Settings, API keys, with trace, metric and log ingestion.
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://api.vitalrix.com/api/v1/traces/otlp/v1/traces
export OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=https://api.vitalrix.com/api/v1/metrics/otlp/v1/metrics
export OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=https://api.vitalrix.com/api/v1/logs/otlp/v1/logs
export OTEL_EXPORTER_OTLP_HEADERS=x-api-key=your_api_keyThrough a Collector. Run an OpenTelemetry Collector next to your app, or as a shared service, when the SDK exports over gRPC or you want one place for batching, sampling and retries. It receives from the SDK and forwards to VitalRix with your key.
receivers:
otlp:
protocols:
grpc: { endpoint: 0.0.0.0:4317 }
http: { endpoint: 0.0.0.0:4318 }
processors:
memory_limiter: { check_interval: 1s, limit_mib: 512 }
batch: {}
exporters:
otlphttp/vitalrix:
traces_endpoint: ${env:VITALRIX_API}/api/v1/traces/otlp/v1/traces
metrics_endpoint: ${env:VITALRIX_API}/api/v1/metrics/otlp/v1/metrics
headers:
x-api-key: ${env:VITALRIX_KEY}
service:
pipelines:
traces: { receivers: [otlp], processors: [memory_limiter, batch], exporters: [otlphttp/vitalrix] }
metrics: { receivers: [otlp], processors: [memory_limiter, batch], exporters: [otlphttp/vitalrix] }docker run -d --name otel-collector -p 4317:4317 -p 4318:4318 \
-e VITALRIX_API=https://api.vitalrix.com -e VITALRIX_KEY=your_api_key \
-v "$PWD/otel-collector.yaml:/etc/otelcol-contrib/config.yaml" \
otel/opentelemetry-collector-contrib:latestCheck that it works
- Send a few requests to the app.
- In VitalRix, open APM: catalog appears in the service catalog within a minute, with request rate, error rate and p95.
- Open an endpoint and then one request to see its trace waterfall, including database spans.
- If nothing arrives, check the exporter's (or the Collector's) logs for export errors: 401 means the key or header is wrong, 402 that a new host is over the plan's APM host allowance. The packages have a
checkcommand that sends one test log.
Add service.version so new releases appear as deploy markers, and put the trace ID in your logs so each trace shows its log lines. See APM and logs, metrics and traces.
Does it work with the Flask development server?
Yes, but the reloader starts the app twice. Disable the reloader when testing instrumentation, and use a production WSGI server for real traffic.
How do I trace background threads?
Pass the current context into the thread (opentelemetry.context.attach) or start a new span in the thread linked to the request.
Check it now, free
- Response time checker: Measure TTFB with DNS, connect, TLS and server time.
Related reading
- OpenTelemetry for Django: Trace a Django app with OpenTelemetry: auto-instrument views and the ORM, run under gunicorn safely, trace Celery tasks and export to VitalRix.
- OpenTelemetry for Go: Instrument a Go service with OpenTelemetry: set up the tracer provider, wrap net/http with otelhttp, pass context everywhere and export the spans.
- OpenTelemetry for PHP and Laravel: Trace a Laravel app with OpenTelemetry: install the PHP extension and auto-instrumentation packages, configure PHP-FPM and trace queries.
- OpenTelemetry for NestJS: Trace a NestJS service with OpenTelemetry: load the SDK before Nest boots, instrument HTTP, Express and NestJS core, and export JSON to VitalRix.
- OpenTelemetry for Next.js: Trace a Next.js app with OpenTelemetry using instrumentation.ts: Node.js runtime setup, JSON export straight to VitalRix, fetch spans and Edge caveats.
- OpenTelemetry for Ruby on Rails: Trace a Ruby on Rails app with OpenTelemetry: gems, an initializer with use_all, ActiveRecord and Sidekiq spans, Puma workers and exporting to VitalRix.
Watch your own site and services with VitalRix
Uptime checks, APM, logs, real-user monitoring, alerts and status pages in one place. Every product has a free tier and no credit card is needed.