How to Use OpenTelemetry for Metrics and Traces in Go

Initialize OpenTelemetry Tracer and Meter providers in Go, then wrap HTTP handlers and database connections to automatically export traces and metrics.

Use the open-telemetry/opentelemetry-go SDK to initialize a TracerProvider and MeterProvider, then configure your HTTP handlers and database drivers to export traces and metrics.

package main

import (
	"context"
	"log"
	"net/http"

	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
	"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
	"go.opentelemetry.io/otel/sdk/metric"
	"go.opentelemetry.io/otel/sdk/trace"
	"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
)

func main() {
	ctx := context.Background()

	// Initialize Tracer
	traceExporter, _ := otlptracehttp.New(ctx)
	tracerProvider := trace.NewTracerProvider(trace.WithBatcher(traceExporter))
	otel.SetTracerProvider(tracerProvider)

	// Initialize Meter
	metricExporter, _ := otlpmetrichttp.New(ctx)
	meterProvider := metric.NewMeterProvider(metric.WithReader(metric.NewPeriodicReader(metricExporter)))
	otel.SetMeterProvider(meterProvider)

	// Wrap HTTP handler
	handler := otelhttp.NewHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Hello, World!"))
	}), "handler")

	log.Fatal(http.ListenAndServe(":8080", handler))
}
  1. Install the SDK and exporters: go get go.opentelemetry.io/otel go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp.
  2. Create a trace.TracerProvider with an OTLP exporter and set it globally using otel.SetTracerProvider.
  3. Create a metric.MeterProvider with an OTLP exporter and set it globally using otel.SetMeterProvider.
  4. Wrap your http.Handler with otelhttp.NewHandler to automatically record request traces and metrics.
  5. For database traces, use the github.com/exaring/otelpgx adapter to wrap your pgx connection.