Sub topic 4
Setting up the OpenTelemetry SDK
This chapter sets up the OpenTelemetry Python SDK so your LLM application can produce and export spans. It assumes you can write Python functions and context managers and have a local Collector available. It also assumes you know what a span is from the previous chapter. The setup has three parts: a provider, a resource, and a span processor with an exporter.
API and SDK are separate packages
OpenTelemetry splits instrumentation into two layers.
- The API (
opentelemetry-api) definestrace.get_tracer,start_as_current_spanand similar calls. Libraries and application code import it. - The SDK (
opentelemetry-sdk) implements those calls. It creates real spans, attaches resources, and sends data to exporters.
If no SDK is configured, API calls do nothing. Your code runs normally and no spans are recorded. This lets library authors instrument freely, and it means a missing SDK setup fails silently. If your traces never arrive, check the setup first.
Install the packages:
pip install opentelemetry-api opentelemetry-sdk opentelemetry-exporter-otlp-proto-httpThe pieces of the setup
| Piece | Role |
|---|---|
| `Resource` | Describes who produces the telemetry, such as the service name and environment. Every span from this provider carries it. |
| `TracerProvider` | The factory for tracers. It owns the resource, the processors, and the sampler. |
| `SpanProcessor` | Receives each span when it starts and ends, and decides when to hand it to the exporter. |
| `SpanExporter` | Serializes finished spans and sends them somewhere, for example over OTLP/HTTP. |
| `Tracer` | The object your code uses to start spans. It is named after the instrumenting module. |
A minimal setup
This is the baseline configuration. It names the service and batches spans to the Collector's default OTLP/HTTP port, 4318.
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
resource = Resource.create({"service.name": "support-agent"})
provider = TracerProvider(resource=resource)
provider.add_span_processor(
BatchSpanProcessor(OTLPSpanExporter(endpoint="http://localhost:4318/v1/traces"))
)
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("support_agent")Two details matter here.
trace.set_tracer_providersets a global provider. It works only once per process. A second call logs a warning and is ignored, so keep setup in one place that runs at startup.- The
endpointargument passed to the exporter constructor is used exactly as written. You must include the/v1/tracespath.
Resources describe the service, not the span
A resource holds attributes that are the same for every span the process emits. Put things here that identify the deployment:
service.name: required in practice. If you omit it, backends showunknown_service.service.version: lets you compare traces before and after a prompt or code release.deployment.environment.name: separates staging from production.
Resource.create also merges in SDK defaults and any values from the environment variables OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES. Values you pass in code take priority over OTEL_RESOURCE_ATTRIBUTES. Using environment variables lets the same container image run in several environments without code changes.
Model name, prompt version, and user ID do not belong in the resource. They vary per call, so they go on spans as attributes.
Batch or simple processor
The span processor controls when spans leave the process.
| Processor | Behavior | Use it for |
|---|---|---|
| `SimpleSpanProcessor` | Exports each span synchronously when it ends. | Tests and debugging. |
| `BatchSpanProcessor` | Queues spans and exports them in a background thread. | Production. |
LLM calls often take seconds, so a synchronous export adds little relative to the call. It still blocks your request thread when the Collector is slow or down. Use the batch processor outside of tests.
BatchSpanProcessor has four tunable settings. The defaults are shown:
max_queue_size=2048: the buffer size. When it is full, new spans are dropped.schedule_delay_millis=5000: how often the worker exports.max_export_batch_size=512: the largest single export.export_timeout_millis=30000: how long one export may take.
Dropping spans when the queue is full is a deliberate design choice. Telemetry should never take your application down. The cost is that an agent producing hundreds of spans per run under heavy load can lose some. If you see incomplete traces, raise max_queue_size before anything else.
A complete, runnable script
This version adds a console exporter for local checks and flushes before exit. The console exporter is a good first test, since it needs no Collector.
import os
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import (
BatchSpanProcessor,
ConsoleSpanExporter,
)
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
def setup_tracing() -> TracerProvider:
resource = Resource.create(
{
"service.name": os.getenv("OTEL_SERVICE_NAME", "support-agent"),
"service.version": "0.1.0",
"deployment.environment.name": os.getenv("APP_ENV", "dev"),
}
)
provider = TracerProvider(resource=resource)
if os.getenv("TRACE_TO_CONSOLE") == "1":
exporter = ConsoleSpanExporter()
else:
exporter = OTLPSpanExporter(endpoint="http://localhost:4318/v1/traces")
provider.add_span_processor(BatchSpanProcessor(exporter))
trace.set_tracer_provider(provider)
return provider
if __name__ == "__main__":
provider = setup_tracing()
tracer = trace.get_tracer("support_agent")
with tracer.start_as_current_span("hello") as span:
span.set_attribute("demo.step", 1)
print("doing work")
provider.shutdown()Run it with TRACE_TO_CONSOLE=1 python tracing_demo.py. You should see the work message and then a JSON span that includes your service.name in its resource section.
Configuring through environment variables
You can configure the exporter through standard variables instead of constructor arguments. If you construct OTLPSpanExporter() with no arguments, it reads them:
OTEL_EXPORTER_OTLP_ENDPOINT: the base URL, such ashttp://localhost:4318. For OTLP/HTTP the SDK appends/v1/tracesitself.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: a signal-specific URL used exactly as given, so include the path.OTEL_EXPORTER_OTLP_HEADERS: comma-separatedkey=valuepairs, typically for authentication to a hosted backend.OTEL_EXPORTER_OTLP_TIMEOUT: the export timeout.
Common errors
- No spans appear and no error is shown. The SDK was never set up, or
set_tracer_providerran after the code that needed it. Confirm startup order. - Collector returns 404. The exporter endpoint is missing
/v1/traces. This happens when you pass a base URL to the constructor. - Connection refused in the logs. The Collector is not running or listens on a different port. The exporter logs the failure and your application continues.
- Service shows as
unknown_service. The resource has noservice.name. - Setup warning "Overriding of current TracerProvider is not allowed". Setup ran twice, often because of a framework reloader or an import side effect.
- Spans show up in a plain script but not under a forking server. Worker processes forked after setup can lose the background export thread. Run setup inside each worker after the fork.
Exercise
Your agent runs as a one-shot script. Spans print correctly with ConsoleSpanExporter, but with the OTLP exporter and BatchSpanProcessor the final spans never reach the Collector, and the Collector log shows no errors. What is the most likely cause, and what are two ways to fix it?
Show answer
The process exits before the batch processor's background thread exports the queued spans (the default delay is 5 seconds). Fix it by calling provider.shutdown() (or provider.force_flush()) before the script ends. Alternatively, use SimpleSpanProcessor so each span is exported synchronously when it ends, which is acceptable for short scripts but not for production services.
Exercise
You pass endpoint="http://localhost:4318" to OTLPSpanExporter and get 404 responses from the Collector. Why, and how would the behavior differ if you set OTELEXPORTEROTLP_ENDPOINT to the same value instead?
Show answer
A constructor endpoint is used exactly as written, so the request goes to the root path instead of /v1/traces. It needs to be "http://localhost:4318/v1/traces". With the OTELEXPORTEROTLP_ENDPOINT environment variable, the SDK appends /v1/traces for OTLP/HTTP, so the base URL works.