Instrument an App with OpenTelemetry, Step by Step
The lab's Collector has run for two lessons, but the only span it has seen came from a test script. When checkout turns slow, you can't yet tell which step is to blame. To fix that, you instrument an app with OpenTelemetry: you add code and libraries that record each request as spans and send them to the Collector. This lesson walks through the lab's instrumented shop and checks that its spans arrive.
Automatic spans and your own spans
Instrumentation is the code that records what an app does as telemetry, here spans, the timed steps a trace is made of. It leaves the app's answers unchanged and costs a little CPU and memory. As What Is OpenTelemetry? explained, code calls the OpenTelemetry API, and the SDK, set up once at startup, records and sends.
Automatic spans come from instrumentation libraries, packages that hook into a popular library: the one for Flask, a Python web framework, makes a span for each HTTP request, and the one for sqlite3, Python's built-in database module, a span for each query. That lesson showed opentelemetry-instrument switching them on with no code changes; this lab does it in code, so you can see each step.
Libraries can't see your business steps: to Flask, the inventory lookup is just code inside a request. For the steps you care about, you add manual spans with the API.
The flowchart follows one /checkout request. Notice that its four spans form one tree and leave the app together.
A span's kind names its role: SERVER for an incoming request, CLIENT for an outgoing call, and INTERNAL, the default for manual spans, for work inside the app.
The setup: SDK, service.name and an exporter
The first shop-demo runs on Python's built-in http.server, which has no instrumentation library. So 04-otel-collector-jaeger/app serves the same routes with Flask, which has one. Its steps, delays and error rates are unchanged, and the inventory lookup now also reads a small SQLite table, so a database span appears.
Step one is the packages, pinned in app/requirements.txt and installed by the Dockerfile:
flask==3.1.3
opentelemetry-api==1.45.2
opentelemetry-sdk==1.45.2
opentelemetry-exporter-otlp-proto-grpc==1.45.2
opentelemetry-instrumentation-flask==0.66b2
opentelemetry-instrumentation-sqlite3==0.66b2
The exporter package sends spans as OTLP over gRPC. The instrumentation packages are in beta, hence the b, and must match the SDK: 0.66b2 goes with 1.45.2.
Step two is setup() in app/telemetry.py, which runs once, before the first request:
resource = Resource.create({"service.name": service_name, "service.version": version})
provider = TracerProvider(resource=resource)
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
trace.set_tracer_provider(provider)
FlaskInstrumentor().instrument_app(app)
SQLite3Instrumentor().instrument()
The resource, which the pipelines lesson described as the attributes that say what sent the telemetry, carries service.name, here shop-demo-otel. Jaeger groups traces by it. Without it, the SDK uses a placeholder that starts with unknown_service.
The tracer provider is the SDK object that creates spans, and set_tracer_provider makes every trace.get_tracer() call use it. A span processor receives each span as it ends. BatchSpanProcessor queues them and, by default, hands up to 512 at a time to the exporter every 5 seconds, so spans reach the Collector a few seconds late. OTLPSpanExporter is the app's exporter, not one of the Collector's.
Point it at the Collector, then add manual spans
With no arguments, OTLPSpanExporter() reads its address from the OTEL_EXPORTER_OTLP_ENDPOINT environment variable. The new service in docker-compose.yml sets it (trimmed):
shop-demo-otel:
profiles: ["app"]
build: ./app
environment:
OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4317
OTEL_PYTHON_FLASK_EXCLUDED_URLS: "health"
ports:
- "127.0.0.1:8001:8001"
otel-collector is the Collector's service name on the lab network and 4317 its OTLP gRPC port. The http:// means plain gRPC without TLS, the encryption behind HTTPS. Without the variable, the exporter tries localhost:4317, and inside a container that is the app itself.
The excluded-URLs variable skips spans for the health check that runs every 10 seconds. A Compose profile, here app, keeps a service out of a plain docker compose up -d, so lessons 12 and 13 still start two services. Naming the service starts it anyway.
Manual spans come from a tracer, trace.get_tracer("shop-demo-otel"). start_as_current_span opens a span and makes it the current span until its with block ends, and new spans become children of the current span. Flask's span is current when checkout() runs, so inventory.lookup becomes its child:
with tracer.start_as_current_span("inventory.lookup") as span:
span.set_attribute("shop.order.id", order_id)
span.set_attribute("shop.order.item_count", items)
lookup_inventory(items)
Inside the block, the sqlite3 library's SELECT span finds inventory.lookup current and becomes its child. payment.charge wraps the payment step the same way. Compare the two versions of checkout(): no line of the shop's logic changed.
Useful attributes, and errors on the span
An attribute, a key-value pair on a span, earns its place if it answers an incident question: which order, and how many items? Keep span names fixed and put changing values such as the order ID in attributes, with a prefix of your own, here shop., so they never clash with official names.
Never record secrets such as passwords, tokens or card numbers, or personal data: anyone who can open Jaeger can read every span. Avoid huge values such as request bodies, too, because the Python SDK sets no length limit by default. The sqlite3 library records each query with its ? placeholders, not the values.
When an exception escapes a span's with block, the SDK records it. A PaymentError leaving payment.charge adds an event, a timestamped note on the span, named exception, with the type, message and stack trace. The span's status becomes Error with the message PaymentError: payment provider timed out, and checkout() then returns HTTP 500.
The Flask instrumentation marks its span Error too, for any 5xx response; a 4xx leaves a server span's status unset. If you handle a failure inside a block, set the status yourself with span.set_status(Status(StatusCode.ERROR, "out of stock")).
Check yourself
You delete OTEL_EXPORTER_OTLP_ENDPOINT from the compose file and recreate the app. /checkout still answers normally, but no spans reach the Collector. Why do both happen?
The exporter falls back to localhost:4317, the container itself, so every export fails. Exports run in the background, apart from requests, so the only sign is warnings in the app's log.
The sqlite3 library knows nothing about your code, yet its SELECT span is a child of inventory.lookup, not of GET /checkout. How?
New spans attach to whichever span is current, and inside the with block that is inventory.lookup. Run the same query outside the block and it would become a child of GET /checkout.
A payment fails and /checkout returns 500. Which of the four spans end with status Error, and why?
payment.charge, because the PaymentError escaped its block, and GET /checkout, because Flask's instrumentation marks a server span Error for a 5xx. inventory.lookup and SELECT ended before the failure, so they stay Unset.
Go deeper
- Unveiling the Power of OpenTelemetry Operator: Simplifying Observability in Kubernetes: how the Operator automates instrumentation on Kubernetes, the setup you did by hand here.