Skip to content

OpenTelemetry guide

OpenTelemetry for Go

Go has no agent that rewrites your code at runtime, so instrumentation is explicit: a tracer provider at startup, wrapped handlers and clients, and context passed through every call.

3 min read10 sectionsUpdated

On this page

Key points

  • Set up a TracerProvider with a batching OTLP exporter in main.
  • otelhttp wraps handlers and HTTP clients.
  • Pass ctx through every function; that is how spans nest.
  • Shut down the provider on exit so the last spans are sent.

Install

bash
go get go.opentelemetry.io/otel \
  go.opentelemetry.io/otel/sdk \
  go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp \
  go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp

Set up tracing in main

main.gogo
package main

import (
	"context"
	"log"
	"net/http"
	"os/signal"
	"syscall"

	"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
	"go.opentelemetry.io/otel/propagation"
	"go.opentelemetry.io/otel/sdk/resource"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
)

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()

	// Endpoint and headers come from OTEL_EXPORTER_OTLP_* variables (the Collector, e.g. http://localhost:4318)
	exp, err := otlptracehttp.New(ctx)
	if err != nil {
		log.Fatal(err)
	}
	// Service name and attributes come from OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES
	res, _ := resource.New(ctx, resource.WithFromEnv(), resource.WithTelemetrySDK(), resource.WithHost())
	tp := sdktrace.NewTracerProvider(sdktrace.WithBatcher(exp), sdktrace.WithResource(res))
	defer tp.Shutdown(context.Background())
	otel.SetTracerProvider(tp)
	otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{}))

	mux := http.NewServeMux()
	mux.HandleFunc("GET /orders/{id}", getOrder)
	srv := &http.Server{Addr: ":8080", Handler: otelhttp.NewHandler(mux, "orders")}
	go srv.ListenAndServe()
	<-ctx.Done()
	srv.Shutdown(context.Background())
}

Pass context everywhere

orders.gogo
var tracer = otel.Tracer("orders")
var client = http.Client{Transport: otelhttp.NewTransport(http.DefaultTransport)}

func getOrder(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()                         // carries the server span
	order, err := loadOrder(ctx, r.PathValue("id"))
	// ...
}

func loadOrder(ctx context.Context, id string) (*Order, error) {
	ctx, span := tracer.Start(ctx, "load order")
	defer span.End()
	req, _ := http.NewRequestWithContext(ctx, "GET", pricingURL+"/prices/"+id, nil)
	resp, err := client.Do(req)                // child span, traceparent header added
	// ...
}

A function that does not accept a context.Context cannot create child spans in the right place. Database libraries have contrib instrumentation too (for example otelsql for database/sql, or the hooks provided by pgx), and every query must use the ...Context variants.

Send it to VitalRix

Shortcut. The VitalRix package does all of the above for you: go get github.com/avinashManiTripathi/vitalrix-sdks/go, then vitalrix.Init(ctx), with vitalrix.Handler for server spans and vitalrix.Logger() for slog. 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 Go 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.

bash
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_key

Through 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.

otel-collector.yamlyaml
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] }
bash
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:latest

Pitfalls

  • Spans never ended leak memory and never export: always defer span.End().
  • Using context.Background() deep in the call stack starts a new trace.
  • High-cardinality span names: use route patterns, not raw paths. With Go 1.22 patterns, prefer the pattern as the span name.
  • Missing shutdown: short-lived programs exit before the batcher flushes.

Check that it works

  1. Send a few requests to the app.
  2. In VitalRix, open APM: orders appears in the service catalog within a minute, with request rate, error rate and p95.
  3. Open an endpoint and then one request to see its trace waterfall, including database spans.
  4. 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 check command 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.

Frequently asked questions

Is there zero-code instrumentation for Go?

An eBPF-based auto-instrumentation project exists, but explicit SDK instrumentation is the most common and the most complete approach today.

Which exporter should I use?

otlptracehttp to a Collector is simple and works through most networks. otlptracegrpc is also fine inside a cluster.

  • OpenTelemetry for FastAPI: Trace a FastAPI service with OpenTelemetry: instrument the app, async database drivers and httpx, run uvicorn workers correctly and export.
  • 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 Flask: Instrument a Flask app with OpenTelemetry, in code or with zero code: trace routes, SQLAlchemy and outgoing calls, and export 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 Python: setup guide: Add OpenTelemetry to a Python service: install the distro, auto-instrument with opentelemetry-instrument, export to VitalRix and add custom spans.

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.