Skip to content
Français
Sync not enabled: your progress stays in this browser My learning
Select theme
Français

OpenTelemetry: universal instrumentation

22 min read
Improve this page

Logo OpenTelemetry

OpenTelemetry (OTel) is the open source standard for instrumenting your applications: you generate traces, metrics and logs once, then send them to any backend. No vendor lock-in, no re-instrumentation if you change your observability stack.

The previous lessons observed an application that was already instrumented; this one shows how to make yours observable. You will go from your first trace to a production-ready configuration: quickstart, auto-instrumentation, business spans, configuration and sampling.

What you will learn

  • Understand OpenTelemetry's layered model (API, SDK, Collector).
  • Watch a first trace go through a test Collector.
  • Instrument an application automatically and then manually.
  • Configure OTel with environment variables, OTLP protocol included.
  • Prepare for production: sampling, propagation, conventions.

Why OpenTelemetry?

Before OpenTelemetry, every observability tool imposed its own agent and its own format. Changing backend meant re-instrumenting every application. OTel breaks this coupling: a single instrumentation, a single protocol (OTLP), and the choice of backend becomes a simple infrastructure decision. That is what made it the de facto standard.

QuestionAnswer
What is it?A set of APIs, SDKs and tools to generate telemetry (traces, metrics, logs)
Who maintains it?CNCF (Cloud Native Computing Foundation), Graduated project since May 11, 2026
Why use it?One standard, multi-language, multi-backend, active community
Which backends?Jaeger, Tempo, Prometheus, Mimir, Loki, Datadog, New Relic, Splunk...

Mental model: how the building blocks fit together

Before coding, understand the 5 layers:

The OpenTelemetry layers: your code calls the API, the SDK collects and exports, the OTLP exporter sends to the Collector, optional but recommended, which distributes to Tempo, Jaeger, Prometheus and Loki.BackendsYour applicationOTLPYour codecalls the APIAPI, stable interfacetracer, meter, loggerSDK: collect, batch, exportTracerProvider, MeterProviderOTLP exportergRPC :4317, HTTP :4318Collector, optional but recommendedbatch, retry, K8s enrichment, filtering, routingTempoJaegerPrometheusLoki
Source · SVG
Esc to close, + and − to zoom, scroll to move around. 100 %
LayerWhat it doesWhere it lives
APIInterface to create spans, metrics, logsIn your code
SDKImplementation: buffering, sampling, exportApp runtime
Auto-instrumentationAutomatically instruments frameworksAgent/wrapper around the app
OTLP exporterSends the signals over OTLPIn the app (SDK)
CollectorReceives, transforms, routesInfrastructure (container/daemon)

Quickstart: your first trace (10 min)

Goal: see a trace go by before coding anything.

  1. Start a Collector with the debug exporter

    Terminal window
    docker run --rm -p 4317:4317 -p 4318:4318 \
    otel/opentelemetry-collector-contrib:0.155.0@sha256:4935caa35e9a4cb387e35732e8fb22b2b5759af8d12e7043357f03837f6e8df5 \
    --config='yaml:
    receivers:
    otlp:
    protocols:
    grpc:
    endpoint: 0.0.0.0:4317
    http:
    endpoint: 0.0.0.0:4318
    exporters:
    debug:
    verbosity: detailed
    service:
    pipelines:
    traces:
    receivers: [otlp]
    exporters: [debug]
    '

    The yaml: prefix is mandatory: without it, --config expects a path or a URI, and the Collector stops right away with Error: invalid uri. Tested on 0.155.0. Once started, it prints the traces it receives in the console.

  2. Send a test trace

    With telemetrygen (OTel test tool):

    Terminal window
    docker run --rm --network host \
    ghcr.io/open-telemetry/opentelemetry-collector-contrib/telemetrygen:v0.155.0@sha256:32d1762abb401e36dd8cfdf60a71075b41bd996a0cfb7c8d2e6eac4d609625b9 \
    traces --otlp-insecure --traces 1
  3. Check the output

    You should see in the Collector logs:

    Span #0
    Name : okey-dokey-0
    Kind : Server
    Span #1
    Name : lets-go
    Kind : Client

    These two names are hard-coded in telemetrygen: lets-go is the client root span, okey-dokey-0 the server child span that simulates the called service. Seeing both confirms that the trace context was propagated from parent to child. The display order follows the arrival of the spans, not their hierarchy: the child comes out first here.

You have a working pipeline. Now let's instrument a real application.

Choosing your mode: auto vs manual

The question is not "auto or manual" but "in which order". Both approaches produce spans in the same trace and combine without conflict: auto-instrumentation intercepts the libraries you did not write (HTTP client, SQL driver, Kafka consumer), manual instrumentation describes what your code does between those calls. Read the third row of the table as the real target in production, the first two as steps towards it.

ModeWhen to use itWhat it covers
Auto-instrumentationQuick start, legacy, standard frameworksHTTP, SQL, Redis, Kafka, gRPC...
Manual instrumentationBusiness logic, custom spansCheckout, payment, PDF generation...
BothReal productionAuto = "plumbing", manual = "business"

Auto-instrumentation by language

Auto-instrumentation injects traces without changing your code for common frameworks (HTTP, DB, messaging). The mechanism differs by language and this changes what you must deploy: Java relies on a JVM agent loaded at startup, Python on a launcher (opentelemetry-instrument) that monkey-patches the libraries, Node.js on a module loaded before the application code with --require, .NET on an explicit registration in the dependency injection container. Go is the exception: its static compilation rules out monkey-patching, so instrumentation goes through explicit wrappers (or through the separate opentelemetry-go-instrumentation project, which relies on eBPF).

Terminal window
# Install the distro (includes SDK + common instrumentations)
pip install opentelemetry-distro
opentelemetry-bootstrap -a install
# Run with auto-instrumentation
opentelemetry-instrument python app.py

Configuration via env vars (recommended):

Terminal window
export OTEL_SERVICE_NAME=checkout-api
export OTEL_EXPORTER_OTLP_PROTOCOL=grpc
export OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317
# Optional: local debug
export OTEL_TRACES_EXPORTER=console

Manual instrumentation: business spans

Auto covers the "pipes" (HTTP, DB). To trace the business logic, add manual spans.

from opentelemetry import trace
tracer = trace.get_tracer(__name__)
def process_checkout(cart_id: str, user_id: str):
with tracer.start_as_current_span("checkout.process") as span:
# Business attributes
span.set_attribute("cart.id", cart_id)
span.set_attribute("user.id", user_id)
span.set_attribute("cart.items_count", 5)
# Child span
with tracer.start_as_current_span("checkout.validate_payment"):
validate_payment()
with tracer.start_as_current_span("checkout.reserve_stock"):
reserve_stock()

Handling errors

A span whose code raised an exception stays green by default: the SDK does not guess that there was an incident. Two distinct calls are needed and they do not do the same thing. set_status(StatusCode.ERROR) marks the span as failed, which makes it stand out in red in the backend and is what your alerts trigger on. record_exception() attaches the stack trace to the span as an event, which gives the diagnostic context. The final raise is essential: without it, you would have traced an error while hiding it from the caller.

from opentelemetry.trace import Status, StatusCode
try:
result = process_payment()
except Exception as e:
span.set_status(Status(StatusCode.ERROR, str(e)))
span.record_exception(e)
raise

Universal configuration (env vars)

Do not hardcode endpoints. Use the standard OTel environment variables:

Terminal window
# Service identity (mandatory)
OTEL_SERVICE_NAME=checkout-api
OTEL_RESOURCE_ATTRIBUTES=service.version=1.2.0,deployment.environment=production
# OTLP export
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317
OTEL_EXPORTER_OTLP_PROTOCOL=grpc # or http/protobuf
# Sampling (production)
OTEL_TRACES_SAMPLER=parentbased_traceidratio
OTEL_TRACES_SAMPLER_ARG=0.1 # 10% of traces
# Propagation
OTEL_PROPAGATORS=tracecontext,baggage
# Debug (dev only)
OTEL_TRACES_EXPORTER=console # prints to stdout

One nuance worth knowing: OTEL_SERVICE_NAME, OTEL_RESOURCE_ATTRIBUTES, OTEL_TRACES_SAMPLER, OTEL_PROPAGATORS and the OTEL_*_EXPORTER variables are specified and behave the same way in every language. Many other variables that you will come across in blog posts, starting with OTEL_LOG_LEVEL, are not in the specification and are only recognized by some SDKs. Before putting one in a production manifest, check it in the SDK configuration of the language concerned.

Production: the 5 critical points

1. Sampling: do not trace 100%

In production, tracing 100% of requests is expensive in storage and adds latency to every call. The point to understand is that the sampling decision is made at the start of the trace and then propagated: that is the whole point of the parentbased_ variant, which guarantees that a trace is complete or absent, never cut off from its last services. A non-parentbased sampler applied service by service produces holey traces, where the root span exists but not the database call that took three seconds.

SamplerDescription
always_onEverything (dev only)
traceidratioX% of traces
parentbased_traceidratioX% unless the parent has decided (recommended)
Terminal window
OTEL_TRACES_SAMPLER=parentbased_traceidratio
OTEL_TRACES_SAMPLER_ARG=0.1 # 10%

2. Propagation: W3C Trace Context

Propagation transmits the trace-id between services. Without it, your traces are fragmented.

traceparent: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01

By default, OTel uses W3C Trace Context. If you have legacy B3 (Zipkin):

Terminal window
OTEL_PROPAGATORS=tracecontext,baggage,b3multi

3. Semantic Conventions: standard attributes

Semantic Conventions are the standardized list of attribute names. Their value is not cosmetic: the prebuilt dashboards, alerting rules and anomaly detection functions of backends rely on these exact names. An attribute named http_status instead of http.response.status_code stays visible in the trace, but no tool will use it automatically. The table below only gives the most common domains; the full specification covers several dozen.

DomainAttributes
HTTPhttp.request.method, url.path, http.response.status_code
Databasedb.system.name, db.namespace, db.operation.name, db.query.text
Messagingmessaging.system, messaging.destination.name

4. Logs: correlation with traces

Without correlation, an error log tells you that a payment failed but not in which request nor after which calls. By injecting trace_id and span_id into every log line, you make it possible to jump directly from the error message to the full trace, and back. The condition is that the log is structured (JSON or logfmt): a free-text message containing the identifier will not be indexed as a field and will remain unusable by the backend.

{
"timestamp": "2026-02-09T10:30:00Z",
"level": "ERROR",
"message": "Payment failed: insufficient funds",
"trace_id": "abc123def456...",
"span_id": "789xyz...",
"service.name": "payment-service"
}

5. Collector: decoupling and governance

In production, do not export directly to the backends. Go through a Collector:

App (SDK) → OTLP → Collector → Backends

Why?

  • Decoupling: change backend without recoding
  • Resilience: the Collector buffers if the backend is down
  • Governance: filtering, PII redaction, K8s enrichment
  • Multiple destinations: traces → Tempo, metrics → Mimir

Anti-patterns (what NOT to do)

The first two rows of the table weigh directly on the observability bill. A unique identifier placed in an attribute multiplies the number of distinct series by the number of users, and this cardinality is what most backends charge for. The next two are security and architecture risks, the last three degrade operability without costing money. Handle them in that order.

Anti-patternConsequenceSolution
Unique IDs in attributesCardinality explosion, costsUse categories (status, region)
Tracing 100% in prodOverhead, storage costsSampling 10-20%
PII/secrets in attributesData leakRedaction via Collector
Exporting directly to the backendVendor lock-in, no governanceGo through a Collector
No service.nameAnonymous, unusable tracesAlways define OTEL_SERVICE_NAME
Ignoring propagationOrphan spans, fragmented tracesCheck propagators + headers
Overly verbose spansNoise, hard to use5-10 attributes max per span

Troubleshooting

Checklist: "I don't see my traces"

Follow these five points in order, from the closest to the code to the closest to the backend. Each one isolates a link of the chain, and stopping at the first one that fails saves you from hunting for a network problem when the SDK produces nothing. Point 1 is checked first: if console shows no span, the problem is in the instrumentation, not in the export.

  1. Does the SDK generate spans?

    Terminal window
    OTEL_TRACES_EXPORTER=console python app.py
    # → You must see spans in stdout
  2. Does the Collector receive the data?

    Enable the debug exporter in the Collector:

    exporters:
    debug:
    verbosity: detailed
  3. Is the network OK?

    Terminal window
    # From the app container
    curl -v http://otel-collector:4318/v1/traces
    # → Must answer (even with a 405 error)
  4. Are the ports correct?

    • 4317 = gRPC
    • 4318 = HTTP

    Check that OTEL_EXPORTER_OTLP_PROTOCOL matches the targeted port. The Java 2.x agent sends http/protobuf without any setting: towards port 4317, the connection is cut (Connection reset) until you set OTEL_EXPORTER_OTLP_PROTOCOL=grpc.

  5. Is propagation configured?

    Without propagation, services do not share the trace-id.

    Terminal window
    OTEL_PROPAGATORS=tracecontext,baggage

Common errors

These four symptoms are told apart by what you already see. If no data arrives, look at the first row: it is a transport problem. If spans arrive but do not attach to one another, it is rows 2 and 3: the trace context is lost, either between two services for lack of a propagator, or inside a single service when an asynchronous task starts without carrying the current context. If everything arrives but the backend cannot name the sender, it is the last row.

SymptomLikely causeSolution
Connection refused :4317Collector not started or wrong portCheck the container/service
Connection reset towards port 4317HTTP protocol sent to a gRPC port (case of the Java 2.x agent without settings)OTEL_EXPORTER_OTLP_PROTOCOL=grpc, or target port 4318
Orphan spans (no parent)Missing propagationCheck OTEL_PROPAGATORS
Fragmented tracesContext lost between async callsPass the context explicitly (trace.use_span() or trace.set_span_in_context() in Python, pass the ctx in Go)
Unknown service in the backendOTEL_SERVICE_NAME not setSet the variable

Metrics (quick overview)

OTel is not limited to traces: the same SDK also produces metrics, with the same service.name and the same resource attributes, which lets you move from a latency graph to the matching traces. The choice of instrument type is not a matter of style, it determines what the backend can compute. A Counter can only answer "how many since startup", a Histogram can answer "what is the 95th percentile", and only the latter lets you set a service level objective on latency.

TypeUseExample
CounterCumulative valuesRequests, errors
GaugeInstantaneous valueMemory, active connections
HistogramDistributionLatency (p50, p95, p99)
from opentelemetry import metrics
meter = metrics.get_meter(__name__)
# Counter
request_counter = meter.create_counter("http.server.requests")
request_counter.add(1, {"method": "GET", "status": "200"})
# Histogram (latency)
latency_histogram = meter.create_histogram("http.server.duration", unit="ms")
latency_histogram.record(45.2, {"method": "GET", "route": "/api/orders"})

Resources

The official references that are authoritative, to consult before putting an environment variable or an attribute in production:

Key takeaways

  • OTel = CNCF standard for traces, metrics, logs, choose it by default
  • Auto-instrumentation: common libraries without changing the code
  • Manual spans for business logic (checkout, payment...)
  • Configure with env vars (OTEL_*), not hardcoded in the code
  • Go through a Collector in production (decoupling, governance)
  • Sampling + redaction = mandatory in prod

FAQ: frequently asked questions

The questions below come up systematically on a first setup: where to start, how to balance auto and manual, which OTLP port to choose, and whether you really need to deploy a Collector.