OpenTelemetry SDKs
OpenTelemetry (OTel) is the CNCF standard for producing telemetry: one API and SDK per language for traces, metrics and logs, one wire protocol (OTLP, over gRPC on port 4317 or HTTP on 4318), shared semantic conventions, and the Collector to process and route it all. Vendors and open-source backends (Jaeger, Tempo, Prometheus, Loki, Elastic, Datadog, Honeycomb…) accept OTLP, so you instrument once and choose backends later.
| Piece | Role |
|---|---|
| API | what libraries and your code call: tracer.Start(ctx, "name"), meter.Int64Counter(…). Safe no-ops if no SDK is configured |
| SDK | the implementation: sampling, batching, resource detection, exporters |
| Instrumentation libraries | ready-made spans/metrics for HTTP servers and clients, gRPC, SQL drivers, Redis, Kafka… |
| Exporter | sends data out: OTLP (to a Collector), or Prometheus /metrics for metrics |
| Zero-code / auto-instrumentation | agents that instrument without code changes: Java agent, Python opentelemetry-instrument, .NET, Node.js; for Go, eBPF-based auto-instrumentation and compile-time tools |
Setting up tracing in linkly (Go)
The SDK is configured once in main; handlers and clients get spans from instrumentation wrappers. This is the shape of linkly's telemetry.go (not runnable here: it needs the OTel modules):
package main
import (
"context"
"net/http"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.37.0"
)
func setupTracing(ctx context.Context, version string) (func(context.Context) error, error) {
// OTEL_EXPORTER_OTLP_ENDPOINT (e.g. http://otel-collector:4317) is read from the environment
exp, err := otlptracegrpc.New(ctx)
if err != nil {
return nil, err
}
res, err := resource.Merge(resource.Default(), resource.NewWithAttributes(semconv.SchemaURL,
semconv.ServiceName("linkly"), semconv.ServiceVersion(version)))
if err != nil {
return nil, err
}
tp := sdktrace.NewTracerProvider(
sdktrace.WithBatcher(exp), // export in batches, in the background
sdktrace.WithResource(res),
sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.TraceIDRatioBased(0.1))),
)
otel.SetTracerProvider(tp)
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
propagation.TraceContext{}, propagation.Baggage{})) // W3C traceparent + baggage
return tp.Shutdown, nil // flush on exit!
}
var tracer = otel.Tracer("linkly/links")
func createLink(w http.ResponseWriter, r *http.Request) {
ctx, span := tracer.Start(r.Context(), "createLink") // child of the HTTP server span
defer span.End()
code, err := store.Insert(ctx, r.FormValue("url")) // pass ctx down: the DB span nests here
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, "insert failed")
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
span.SetAttributes(attribute.String("linkly.code", code))
w.WriteHeader(http.StatusCreated)
}
func routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("POST /links", createLink)
// otelhttp creates a SERVER span per request, extracts traceparent, records method/route/status
return otelhttp.NewHandler(mux, "linkly")
}The rules hidden in that code:
- Pass
ctxeverywhere. The current span lives in thecontext.Context; a function that drops it starts a new, disconnected trace. - Always
End()spans (withdefer), or they are never exported. - Shut down the provider on exit so the last batch is flushed.
- Use
pgx's OTel tracer (orotelsql),redisotelfor go-redis, andotelhttp.NewTransportfor outgoing HTTP: libraries create the CLIENT spans and injecttraceparentfor you.
Most settings can come from standard environment variables instead of code, which is how Kubernetes manifests usually set them:
env:
- name: OTEL_SERVICE_NAME
value: linkly
- name: OTEL_EXPORTER_OTLP_ENDPOINT
value: http://otel-collector.observability:4317
- name: OTEL_TRACES_SAMPLER
value: parentbased_traceidratio
- name: OTEL_TRACES_SAMPLER_ARG
value: "0.1"
- name: OTEL_RESOURCE_ATTRIBUTES
value: deployment.environment.name=prod,service.namespace=linksWhat a tracer does, in miniature
The SDK's core idea is small: a span stores its trace ID, its own ID and its parent's, and the current span travels inside context.Context. This standard-library model implements Start/End that way (IDs from a counter, times from a fake clock) and prints the spans in the order they are exported:
package main
import (
"context"
"fmt"
)
type span struct {
traceID, spanID, parentID string
name string
start, end int
attrs map[string]string
}
type ctxKey struct{}
type tracer struct {
nextID int
clock int
exported []*span
}
func (t *tracer) newID(n int) string { t.nextID++; return fmt.Sprintf("%0*x", n, t.nextID) }
// Start creates a child of the span in ctx, or a new trace if there is none.
func (t *tracer) Start(ctx context.Context, name string) (context.Context, *span) {
s := &span{name: name, start: t.clock, attrs: map[string]string{}}
if parent, ok := ctx.Value(ctxKey{}).(*span); ok {
s.traceID, s.parentID = parent.traceID, parent.spanID
} else {
s.traceID = t.newID(32)
}
s.spanID = t.newID(16)
return context.WithValue(ctx, ctxKey{}, s), s
}
func (t *tracer) End(s *span) { s.end = t.clock; t.exported = append(t.exported, s) }
func (t *tracer) work(ms int) { t.clock += ms }
func insertLink(ctx context.Context, t *tracer) {
_, s := t.Start(ctx, "INSERT links")
defer t.End(s)
s.attrs["db.system.name"] = "postgresql"
t.work(9)
}
func main() {
t := &tracer{}
ctx, root := t.Start(context.Background(), "POST /links")
root.attrs["http.route"] = "/links"
t.work(1)
insertLink(ctx, t) // ctx carries root: the INSERT becomes its child
insertLink(context.Background(), t) // the classic bug: ctx dropped, a new trace starts
t.work(2)
t.End(root)
for _, s := range t.exported {
parent := s.parentID
if parent == "" {
parent = "(root)"
}
fmt.Printf("trace=%s span=%s parent=%-16s %-12s %2d-%2d ms %v\n",
s.traceID[24:], s.spanID, parent, s.name, s.start, s.end, s.attrs)
}
}trace=00000001 span=0000000000000003 parent=0000000000000002 INSERT links 1-10 ms map[db.system.name:postgresql]
trace=00000004 span=0000000000000005 parent=(root) INSERT links 10-19 ms map[db.system.name:postgresql]
trace=00000001 span=0000000000000002 parent=(root) POST /links 0-21 ms map[http.route:/links]
(Trace IDs are printed as their last 8 hex digits.) The first INSERT shares the request's trace ID and has the root as its parent. The second one, called with context.Background(), starts a brand-new trace with no parent: in a tracing UI it shows up as a lonely one-span trace, and the request looks faster than it was. Spans are exported when they end, children before parents, which is why backends assemble trees from flat lists.
Metrics and logs with OTel
- Metrics API:
meter.Int64Counter("linkly.links.created"),meter.Float64Histogram("http.server.request.duration", metric.WithUnit("s")). Exported over OTLP to the Collector (or to Prometheus's OTLP receiver), where names are translated to Prometheus style (linkly_links_created_total,http_server_request_duration_seconds) unless UTF-8 names are kept. - Logs: OTel doesn't replace your logger; a bridge (for Go:
otelslog) sendsslogrecords as OTel logs with the currenttrace_id/span_idattached automatically. Alternatively keep logging JSON to stdout and add the IDs yourself (Structured JSON Logging).
Test yourself
What happens if a function creates a span from context.Background() instead of the request's context?
- Nothing
- The span starts a new, unrelated trace instead of joining the request's
- The SDK panics
- The span is dropped
Which environment variable points an OTel SDK at the Collector?
OTEL_COLLECTOR_URLOTEL_EXPORTER_OTLP_ENDPOINTJAEGER_ENDPOINTOTLP_HOST
Why must the TracerProvider be shut down when the program exits?
- To free memory
- Spans are exported in batches; shutdown flushes the last batch
- To close the HTTP server
- It isn't necessary