OpenTelemetry
Go
Quick Start

Go (OpenTelemetry)

Let a coding agent do this setup
1Install the Traceway skills
2Run it in Claude Code

It adds OpenTelemetry to your Go service and checks that data arrives. How the setup skill works

Instrument a Go service with the OpenTelemetry Go SDK and export traces, logs and metrics to Traceway over OTLP/HTTP.

This guide uses the standard library's net/http and log/slog. Go has no agent that patches a running program, so the setup is a small amount of code: one file that starts the SDK and one wrapper around your handlers. If you use Gin, Chi, Echo or Fiber, replace otelhttp with that framework's OpenTelemetry middleware and keep everything else.

Requirements

  • Go 1.26 or newer. The current SDK modules declare go 1.26.0.
  • A Traceway project created with framework OpenTelemetry, and that project's token.

Install

go get go.opentelemetry.io/otel \
  go.opentelemetry.io/otel/sdk \
  go.opentelemetry.io/otel/sdk/metric \
  go.opentelemetry.io/otel/sdk/log \
  go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp \
  go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp \
  go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp \
  go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp \
  go.opentelemetry.io/contrib/bridges/otelslog

The API, the SDK and each exporter are separate modules. With the SDK alone, spans are recorded and thrown away. This guide was checked with otel v1.47.0, otelhttp v0.72.0 and otelslog v0.21.0.

Configure

The exporters and the SDK read these from the process environment. Nothing about the destination is written in code.

export OTEL_SERVICE_NAME=my-go-service
export OTEL_RESOURCE_ATTRIBUTES="service.version=1.0.0"
export OTEL_EXPORTER_OTLP_ENDPOINT=https://cloud.tracewayapp.com/api/otel
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer your-project-token"
export OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=delta
  • OTEL_EXPORTER_OTLP_ENDPOINT takes the base URL. The exporters append /v1/traces, /v1/metrics and /v1/logs themselves.
  • OTEL_SERVICE_NAME becomes the Server Name on every endpoint, task and issue. Version travels in OTEL_RESOURCE_ATTRIBUTES. There is no OTEL_SERVICE_VERSION variable.
  • The temporality line makes counters send what changed since the last export. Without it the SDK re-sends the running total every time, and a sum over the chart adds the same events again and again.
  • The three otlp...http exporters always speak OTLP/HTTP, which is what Traceway accepts, so OTEL_EXPORTER_OTLP_PROTOCOL is not needed here.

Check the path. If the endpoint is your server's address without /api/otel, the dashboard answers the export with 200 and a web page. The exporter takes that as success, so nothing is stored and nothing is logged. A wrong token is visible: the exporter prints 401 Unauthorized on stderr.

Start the SDK

Add this file next to main.go. It builds the three pipelines and returns one function that flushes them on exit.

otel.go
package main
 
import (
	"context"
	"errors"
 
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp"
	"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
	"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
	"go.opentelemetry.io/otel/log/global"
	"go.opentelemetry.io/otel/propagation"
	sdklog "go.opentelemetry.io/otel/sdk/log"
	sdkmetric "go.opentelemetry.io/otel/sdk/metric"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
)
 
func setupOTelSDK(ctx context.Context) (shutdown func(context.Context) error, err error) {
	var shutdownFuncs []func(context.Context) error
	shutdown = func(ctx context.Context) error {
		var err error
		for _, fn := range shutdownFuncs {
			err = errors.Join(err, fn(ctx))
		}
		shutdownFuncs = nil
		return err
	}
	defer func() {
		if err != nil {
			err = errors.Join(err, shutdown(ctx))
		}
	}()
 
	otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
		propagation.TraceContext{},
		propagation.Baggage{},
	))
 
	traceExporter, err := otlptracehttp.New(ctx)
	if err != nil {
		return nil, err
	}
	tracerProvider := sdktrace.NewTracerProvider(sdktrace.WithBatcher(traceExporter))
	shutdownFuncs = append(shutdownFuncs, tracerProvider.Shutdown)
	otel.SetTracerProvider(tracerProvider)
 
	metricExporter, err := otlpmetrichttp.New(ctx)
	if err != nil {
		return nil, err
	}
	meterProvider := sdkmetric.NewMeterProvider(
		sdkmetric.WithReader(sdkmetric.NewPeriodicReader(metricExporter)),
		sdkmetric.WithView(sdkmetric.NewView(
			sdkmetric.Instrument{Name: "http.server.*"},
			sdkmetric.Stream{Aggregation: sdkmetric.AggregationDrop{}},
		)),
	)
	shutdownFuncs = append(shutdownFuncs, meterProvider.Shutdown)
	otel.SetMeterProvider(meterProvider)
 
	logExporter, err := otlploghttp.New(ctx)
	if err != nil {
		return nil, err
	}
	loggerProvider := sdklog.NewLoggerProvider(
		sdklog.WithProcessor(sdklog.NewBatchProcessor(logExporter)),
	)
	shutdownFuncs = append(shutdownFuncs, loggerProvider.Shutdown)
	global.SetLoggerProvider(loggerProvider)
 
	return shutdown, nil
}

Three lines in it are easy to leave out:

  • The propagator. Go's default propagator does nothing, so without SetTextMapPropagator an incoming traceparent header is ignored and traces across services never link. OTEL_PROPAGATORS is not read.
  • The view. otelhttp records http.server.* histograms, one series per route, method and status. Traceway already computes request counts and latency from spans, so the view drops them and keeps your own metrics.
  • The shutdown function. Spans are batched for 5 seconds, logs for 1 second and metrics for 60. Call the returned function before the process exits, or the last batch is lost.

Instrument the Server

This is a complete service with a parametrized route, a route that panics, and a background job.

main.go
package main
 
import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"log/slog"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
 
	"go.opentelemetry.io/contrib/bridges/otelslog"
	"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/metric"
	"go.opentelemetry.io/otel/trace"
)
 
const name = "example.com/my-go-service"
 
var (
	tracer = otel.Tracer(name)
	meter  = otel.Meter(name)
	logger = slog.New(slog.NewMultiHandler(
		slog.NewTextHandler(os.Stderr, nil),
		otelslog.NewHandler(name),
	))
 
	sessionsCleaned metric.Int64Counter
)
 
func main() {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
 
	shutdown, err := setupOTelSDK(ctx)
	if err != nil {
		log.Fatal(err)
	}
 
	sessionsCleaned, err = meter.Int64Counter("app.sessions_cleaned",
		metric.WithDescription("Expired sessions removed by the cleanup job"))
	if err != nil {
		log.Fatal(err)
	}
 
	srv := &http.Server{Addr: ":" + os.Getenv("PORT"), Handler: newHTTPHandler()}
	go func() {
		<-ctx.Done()
		shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
		defer cancel()
		_ = srv.Shutdown(shutdownCtx)
	}()
	if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
		log.Print(err)
	}
 
	flushCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := shutdown(flushCtx); err != nil {
		log.Print(err)
	}
}
 
func newHTTPHandler() http.Handler {
	mux := http.NewServeMux()
 
	handle := func(pattern string, handler http.HandlerFunc) {
		mux.Handle(pattern, otelhttp.NewHandler(recoverPanics(handler), pattern))
	}
	handle("GET /users/{id}", getUser)
	handle("GET /boom", boom)
	handle("GET /run-job", runJob)
 
	return mux
}
 
func getUser(w http.ResponseWriter, r *http.Request) {
	id := r.PathValue("id")
	logger.InfoContext(r.Context(), "looking up user "+id)
 
	user := loadUser(r.Context(), id)
 
	w.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(w).Encode(user)
}
 
func loadUser(ctx context.Context, id string) map[string]string {
	_, span := tracer.Start(ctx, "load-user", trace.WithAttributes(attribute.String("user.id", id)))
	defer span.End()
 
	time.Sleep(20 * time.Millisecond)
	return map[string]string{"id": id, "name": "User " + id}
}
 
func boom(w http.ResponseWriter, r *http.Request) {
	panic(errors.New("payment provider unreachable"))
}
 
func runJob(w http.ResponseWriter, r *http.Request) {
	cleanupExpiredSessions(r.Context())
	fmt.Fprintln(w, "ok")
}
 
func cleanupExpiredSessions(ctx context.Context) {
	ctx, span := tracer.Start(ctx, "cleanup-expired-sessions",
		trace.WithNewRoot(),
		trace.WithSpanKind(trace.SpanKindConsumer),
	)
	defer span.End()
 
	time.Sleep(50 * time.Millisecond)
	sessionsCleaned.Add(ctx, 7, metric.WithAttributes(attribute.String("job", "cleanup-expired-sessions")))
}
 
func recoverPanics(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			rec := recover()
			if rec == nil {
				return
			}
			if rec == http.ErrAbortHandler {
				panic(rec)
			}
			err, ok := rec.(error)
			if !ok {
				err = fmt.Errorf("%v", rec)
			}
			span := trace.SpanFromContext(r.Context())
			span.RecordError(err, trace.WithStackTrace(true))
			span.SetStatus(codes.Error, err.Error())
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		}()
		next.ServeHTTP(w, r)
	})
}

Run it with the variables from Configure set:

PORT=8080 go run .

The sections below explain the parts of that file you will copy into your own service.

Endpoints: Wrap Each Handler, Not the Mux

otelhttp takes the route from the pattern that http.ServeMux matched. It reads that pattern when the span starts, so the wrapper has to sit behind the mux:

mux.Handle("GET /users/{id}", otelhttp.NewHandler(handler, "GET /users/{id}"))

The form most examples show, otelhttp.NewHandler(mux, "server"), starts the span before the mux has matched anything. The span then has no http.route, Traceway falls back to the URL, and Endpoints fills with one row per id: GET /users/101, GET /users/102, GET /users/103.

With the wrapper behind the mux you get one row, GET /users/{id}. Older snippets call otelhttp.WithRouteTag for this. That function was removed in otelhttp v0.65.0 and is no longer needed.

Exceptions

A panic in a handler does not give you a usable Issue by itself. net/http recovers it and closes the connection, so the client gets an empty reply instead of a 500, and the span carries the panic message without a stack trace.

The recoverPanics middleware in main.go fixes that. It has to run inside otelhttp, so it can reach the request span:

span := trace.SpanFromContext(r.Context())
span.RecordError(err, trace.WithStackTrace(true))
span.SetStatus(codes.Error, err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)

trace.WithStackTrace(true) is what puts the goroutine stack on the Issue. Use the same three calls for an error you handle yourself, and return a 500 when you record one, so the endpoint row and the Issue agree.

Logs

otelslog.NewHandler sends slog records to Traceway. slog.NewMultiHandler keeps them on stderr as well.

Pass the request context, or the line cannot be linked to its trace:

logger.InfoContext(r.Context(), "looking up user "+id)

logger.Info(...) without a context still arrives, with an empty trace id, so it does not show on the endpoint's Logs card. The otelslog handler has no level filter of its own: every record that reaches it is exported, Debug included.

Background Tasks

A cron job or queue consumer appears under Tasks when its span has kind CONSUMER. A root span with the default kind is dropped.

ctx, span := tracer.Start(ctx, "cleanup-expired-sessions",
	trace.WithNewRoot(),
	trace.WithSpanKind(trace.SpanKindConsumer),
)
defer span.End()

The span name is the task name, so keep it stable and put job ids and batch sizes in attributes. trace.WithNewRoot() is only needed when the job is started from inside a request, as it is in this example. A job started from a ticker or a queue has no parent span to detach from.

Custom Metrics

Ask the global meter for an instrument and record on it:

sessionsCleaned, err := meter.Int64Counter("app.sessions_cleaned")
sessionsCleaned.Add(ctx, 7, metric.WithAttributes(attribute.String("job", "cleanup-expired-sessions")))

The counter appears in metric discovery as app.sessions_cleaned, with job as a tag you can group by. Metrics export every 60 seconds by default. While you are checking the integration, set OTEL_METRIC_EXPORT_INTERVAL=5000, and remove it afterwards.

Verify It Worked

Start the service, then send a few requests:

curl localhost:8080/users/101
curl localhost:8080/users/102
curl localhost:8080/users/103
curl localhost:8080/boom
curl localhost:8080/run-job

Set the dashboard time picker to the last 15 minutes and check:

  1. Endpoints. One row GET /users/{id} with a count of 3, and GET /boom with status 500. Three rows with ids in them means the handler is wrapped in front of the mux.
  2. Issues. payment provider unreachable with a stack that includes main.boom.
  3. Logs. Three looking up user lines, each linked to its trace.
  4. Tasks. cleanup-expired-sessions.
  5. Metrics. app.sessions_cleaned in metric discovery, and no http.server.* names.

Nothing at all? Check the endpoint path first, then look at stderr for 401 Unauthorized.

Next Steps

  • Traces: how OTel spans map to Endpoints, Tasks and Issues
  • Logs: log record mapping and severity handling
  • Metrics: supported metric types and histogram handling
  • Overview: protocol details, authentication, and a "nothing is showing up" checklist