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))
}
- 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. - Create a
trace.TracerProviderwith an OTLP exporter and set it globally usingotel.SetTracerProvider. - Create a
metric.MeterProviderwith an OTLP exporter and set it globally usingotel.SetMeterProvider. - Wrap your
http.Handlerwithotelhttp.NewHandlerto automatically record request traces and metrics. - For database traces, use the
github.com/exaring/otelpgxadapter to wrap yourpgxconnection.