Getting Started by Example

Get telemetry for your app in less than 5 minutes!

This page will show you how to get started with OpenTelemetry in Go.

You will learn how you can instrument a simple application manually, in such a way that traces, metrics, and logs are emitted to the console.

Prerequisites

Ensure that you have the following installed locally:

  • Go 1.26 or greater

Example application

The following example uses a basic net/http application. If you are not using net/http, that’s OK — you can use OpenTelemetry Go with other web frameworks as well, such as Gin and Echo. For a complete list of libraries for supported frameworks, see the registry.

For more elaborate examples, see examples.

Setup

To begin, set up a go.mod in a new directory:

go mod init dice

Create and launch an HTTP server

In that same folder, create a file called app.go and add the following code to the file:

package main

import (
	"context"
	"encoding/json"
	"log"
	"net"
	"net/http"
	"os"
	"os/signal"
	"strconv"
	"time"
)

func main() {
	if err := run(); err != nil {
		log.Fatalln(err)
	}
}

func run() (err error) {
	// Handle SIGINT (CTRL+C) gracefully.
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()

	// Start HTTP server.
	port := os.Getenv("APPLICATION_PORT")
	if port == "" {
		port = "8080"
	}

	srv := &http.Server{
		Addr:         ":" + port,
		BaseContext:  func(net.Listener) context.Context { return ctx },
		ReadTimeout:  time.Second,
		WriteTimeout: 10 * time.Second,
		Handler:      newHTTPHandler(),
	}
	srvErr := make(chan error, 1)
	go func() {
		log.Println("Running HTTP server...")
		srvErr <- srv.ListenAndServe()
	}()

	// Wait for interruption.
	select {
	case err = <-srvErr:
		// Error when starting HTTP server.
		return err
	case <-ctx.Done():
		// Wait for first CTRL+C.
		// Stop receiving signal notifications as soon as possible.
		stop()
	}

	// When Shutdown is called, ListenAndServe immediately returns ErrServerClosed.
	err = srv.Shutdown(context.Background())
	return err
}

func newHTTPHandler() http.Handler {
	mux := http.NewServeMux()

	// Register handlers.
	mux.HandleFunc("/rolldice", handleRolldice)
	return mux
}

func handleRolldice(w http.ResponseWriter, r *http.Request) {
	// Parse query parameters.
	rollsParam := r.URL.Query().Get("rolls")
	player := r.URL.Query().Get("player")

	// Default rolls = 1 if not defined.
	if rollsParam == "" {
		rollsParam = "1"
	}

	// Check if rolls is a number.
	rolls, err := strconv.Atoi(rollsParam)
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusBadRequest)
		msg := "Parameter rolls must be a positive integer"
		_ = json.NewEncoder(w).Encode(map[string]string{
			"status":  "error",
			"message": msg,
		})
		log.Printf("WARN: %s", msg)
		return
	}

	results, err := rolldice(rolls)
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusInternalServerError)
		log.Printf("ERROR: %v", err)
		return
	}

	if player == "" {
		log.Printf("DEBUG: anonymous player rolled %v", results)
	} else {
		log.Printf("DEBUG: player=%s rolled %v", strconv.Quote(player), results)
	}
	log.Printf("INFO: %s %s -> 200 OK", strconv.Quote(r.Method), strconv.Quote(r.URL.String()))

	if len(results) == 1 {
		writeJSON(w, results[0])
	} else {
		writeJSON(w, results)
	}
}

func writeJSON(w http.ResponseWriter, v any) {
	data, err := json.Marshal(v)
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusInternalServerError)
		log.Printf("ERROR: %v", err)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	_, _ = w.Write(data)
}

Create another file called library.go and add the following code to the file:

package main

import (
	"errors"
	"math/rand/v2"
)

func rolldice(rolls int) ([]int, error) {
	const maxRolls = 1000 // Arbitrary limit to prevent Slice memory allocation with excessive size value.

	if rolls > maxRolls {
		return nil, errors.New("rolls parameter exceeds maximum allowed value")
	}

	if rolls <= 0 {
		return nil, errors.New("rolls must be positive")
	}

	if rolls == 1 {
		return []int{rollOnce()}, nil
	}

	results := make([]int, rolls)
	for i := range rolls {
		results[i] = rollOnce()
	}
	return results, nil
}

// rollOnce returns a random number between 1 and 6.
func rollOnce() int {
	roll := 1 + rand.IntN(6) //nolint:gosec // G404: Use of weak random number generator (math/rand instead of crypto/rand) is ignored as this is not security-sensitive.
	return roll
}

Build and run the application with the following command:

go run .

Open http://localhost:8080/rolldice in your browser to roll one die. To roll three dice for a named player, open http://localhost:8080/rolldice?player=Alice&rolls=3. Stop the server with Ctrl+C before adding instrumentation.

Add OpenTelemetry Instrumentation

Now we’ll show how to add OpenTelemetry instrumentation to the sample app. If you are using your own application, you can follow along, just note that your code may be slightly different.

Initialize the OpenTelemetry SDK

First, we’ll initialize the OpenTelemetry SDK. This is required for any application that exports telemetry.

Create otel.go with OpenTelemetry SDK bootstrapping code:

package main

import (
	"context"
	"errors"
	"time"

	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/exporters/stdout/stdoutlog"
	"go.opentelemetry.io/otel/exporters/stdout/stdoutmetric"
	"go.opentelemetry.io/otel/exporters/stdout/stdouttrace"
	"go.opentelemetry.io/otel/propagation"
	"go.opentelemetry.io/otel/sdk/log"
	"go.opentelemetry.io/otel/sdk/metric"
	"go.opentelemetry.io/otel/sdk/resource"
	"go.opentelemetry.io/otel/sdk/trace"

	"go.opentelemetry.io/contrib/bridges/otelslog"
)

var logger = otelslog.NewLogger(name)

// setupOTelSDK bootstraps the OpenTelemetry pipeline.
// If it does not return an error, make sure to call shutdown for proper cleanup.
func setupOTelSDK(ctx context.Context) (func(context.Context) error, error) {
	var shutdownFuncs []func(context.Context) error
	var err error

	// shutdown calls cleanup functions registered via shutdownFuncs.
	// The errors from the calls are joined.
	// Each registered cleanup will be invoked once.
	shutdown := func(ctx context.Context) error {
		var err error
		for _, fn := range shutdownFuncs {
			err = errors.Join(err, fn(ctx))
		}
		shutdownFuncs = nil
		return err
	}

	// handleErr calls shutdown for cleanup and makes sure that all errors are returned.
	handleErr := func(inErr error) {
		err = errors.Join(inErr, shutdown(ctx))
	}

	res, resErr := resource.New(
		ctx,
		resource.WithFromEnv(), // Parses OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES.
		resource.WithProcess(),
		resource.WithHost(),
		resource.WithTelemetrySDK(),
		resource.WithOS(),
		resource.WithContainer(),
	)
	if resErr != nil {
		handleErr(resErr)
		return shutdown, resErr
	}

	// Set up propagator.
	prop := newPropagator()
	otel.SetTextMapPropagator(prop)

	// Set up trace provider.
	tracerProvider, err := newTracerProvider(res)
	if err != nil {
		handleErr(err)
		return shutdown, err
	}
	shutdownFuncs = append(shutdownFuncs, tracerProvider.Shutdown)
	otel.SetTracerProvider(tracerProvider)

	// Set up meter provider.
	meterProvider, err := newMeterProvider(res)
	if err != nil {
		handleErr(err)
		return shutdown, err
	}
	shutdownFuncs = append(shutdownFuncs, meterProvider.Shutdown)
	otel.SetMeterProvider(meterProvider)

	// Set up logger provider.
	loggerProvider, err := newLoggerProvider(res)
	if err != nil {
		handleErr(err)
		return shutdown, err
	}
	shutdownFuncs = append(shutdownFuncs, loggerProvider.Shutdown)
	otel.SetLoggerProvider(loggerProvider)

	return shutdown, err
}

func newPropagator() propagation.TextMapPropagator {
	return propagation.NewCompositeTextMapPropagator(
		propagation.TraceContext{},
		propagation.Baggage{},
	)
}

func newTracerProvider(res *resource.Resource) (*trace.TracerProvider, error) {
	traceExporter, err := stdouttrace.New(
		stdouttrace.WithPrettyPrint(),
	)
	if err != nil {
		return nil, err
	}

	tracerProvider := trace.NewTracerProvider(
		trace.WithBatcher(traceExporter,
			// Default is 5s. Set to 1s for demonstrative purposes.
			trace.WithBatchTimeout(time.Second)),
		trace.WithResource(res),
	)
	return tracerProvider, nil
}

func newMeterProvider(res *resource.Resource) (*metric.MeterProvider, error) {
	metricExporter, err := stdoutmetric.New(stdoutmetric.WithPrettyPrint())
	if err != nil {
		return nil, err
	}

	meterProvider := metric.NewMeterProvider(
		metric.WithReader(metric.NewPeriodicReader(metricExporter,
			// Default is 1m. Set to 3s for demonstrative purposes.
			metric.WithInterval(3*time.Second))),
		metric.WithResource(res),
	)
	return meterProvider, nil
}

func newLoggerProvider(res *resource.Resource) (*log.LoggerProvider, error) {
	logExporter, err := stdoutlog.New(stdoutlog.WithPrettyPrint())
	if err != nil {
		return nil, err
	}

	loggerProvider := log.NewLoggerProvider(
		log.WithProcessor(log.NewBatchProcessor(logExporter)),
		log.WithResource(res),
	)
	return loggerProvider, nil
}

If you’re only using tracing or metrics, you can omit the corresponding TracerProvider or MeterProvider initialization code.

Instrument the HTTP server

Now that we have the OpenTelemetry SDK initialized, we can instrument the HTTP server.

Replace app.go to initialize the OpenTelemetry SDK and instrument the HTTP server with the otelhttp instrumentation library. The handler also uses the OpenTelemetry log bridge to send application logs to the console:

package main

import (
	"context"
	"encoding/json"
	"errors"
	"log"
	"net"
	"net/http"
	"os"
	"os/signal"
	"strconv"
	"time"

	"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
)

func main() {
	if err := run(); err != nil {
		log.Fatalln(err)
	}
}

func run() error {
	// Handle SIGINT (CTRL+C) gracefully.
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()

	// Set up OpenTelemetry.
	otelShutdown, err := setupOTelSDK(ctx)
	if err != nil {
		return err
	}
	// Handle shutdown properly so nothing leaks.
	defer func() {
		err = errors.Join(err, otelShutdown(context.Background()))
	}()

	// Start HTTP server.
	port := os.Getenv("APPLICATION_PORT")
	if port == "" {
		port = "8080"
	}
	srv := &http.Server{
		Addr:         ":" + port,
		BaseContext:  func(net.Listener) context.Context { return ctx },
		ReadTimeout:  time.Second,
		WriteTimeout: 10 * time.Second,
		Handler:      newHTTPHandler(),
	}
	srvErr := make(chan error, 1)
	go func() {
		srvErr <- srv.ListenAndServe()
	}()

	// Wait for interruption.
	select {
	case err = <-srvErr:
		// Error when starting HTTP server.
		return err
	case <-ctx.Done():
		// Wait for first CTRL+C.
		// Stop receiving signal notifications as soon as possible.
		stop()
	}

	// When Shutdown is called, ListenAndServe immediately returns ErrServerClosed.
	err = srv.Shutdown(context.Background())
	return err
}

func newHTTPHandler() http.Handler {
	mux := http.NewServeMux()

	// Register handlers.
	mux.Handle("/rolldice", http.HandlerFunc(handleRolldice))

	// Add HTTP instrumentation for the whole server.
	handler := otelhttp.NewHandler(mux, "/")
	return handler
}

func handleRolldice(w http.ResponseWriter, r *http.Request) {
	// Parse query parameters.
	rollsParam := r.URL.Query().Get("rolls")
	player := r.URL.Query().Get("player")

	// Default rolls = 1 if not defined.
	if rollsParam == "" {
		rollsParam = "1"
	}

	// Check if rolls is a number.
	rolls, err := strconv.Atoi(rollsParam)
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusBadRequest)
		msg := "Parameter rolls must be a positive integer"
		_ = json.NewEncoder(w).Encode(map[string]string{
			"status":  "error",
			"message": msg,
		})
		logger.WarnContext(r.Context(), msg)
		return
	}

	results, err := rollDice(r.Context(), rolls)
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusInternalServerError)
		logger.ErrorContext(r.Context(), err.Error())
		return
	}

	if player == "" {
		logger.DebugContext(r.Context(), "anonymous player rolled", "results", results)
	} else {
		logger.DebugContext(r.Context(), "player rolled dice", "player", player, "results", results)
	}
	logger.InfoContext(r.Context(), "Some player rolled a dice.", "method", r.Method, "path", r.URL.Path, "status", http.StatusOK)

	w.Header().Set("Content-Type", "application/json")
	if len(results) == 1 {
		writeJSON(r.Context(), w, results[0])
	} else {
		writeJSON(r.Context(), w, results)
	}
}

func writeJSON(ctx context.Context, w http.ResponseWriter, v any) {
	data, err := json.Marshal(v)
	if err != nil {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusInternalServerError)
		logger.ErrorContext(ctx, "json encode failed", "error", err)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	_, _ = w.Write(data)
}

Add Custom Instrumentation

Instrumentation libraries capture telemetry at the edges of your systems, such as inbound and outbound HTTP requests, but they don’t capture what’s going on in your application. For that you’ll need to write some custom manual instrumentation.

Replace library.go with the dice logic instrumented using the OpenTelemetry API. The code adds spans for the roll operation and for each die, and records metrics for the number of dice rolled and their outcomes:

package main

import (
	"context"
	"errors"
	"math/rand/v2"
	"sync/atomic"

	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/codes"
	"go.opentelemetry.io/otel/metric"
)

const name = "go.opentelemetry.io/contrib/examples/dice"

var (
	tracer = otel.Tracer(name)
	meter  = otel.Meter(name)

	rollCnt        metric.Int64Counter
	outcomeHist    metric.Int64Histogram
	lastRollsGauge metric.Int64ObservableGauge
	lastRolls      atomic.Int64
)

func init() {
	var err error
	rollCnt, err = meter.Int64Counter("dice.rolls",
		metric.WithDescription("Number of dice rolled"),
		metric.WithUnit("{roll}"))
	if err != nil {
		panic(err)
	}

	outcomeHist, err = meter.Int64Histogram(
		"dice.outcome",
		metric.WithDescription("Distribution of dice outcomes (1-6)"),
		metric.WithUnit("{count}"),
	)
	if err != nil {
		panic(err)
	}

	lastRollsGauge, err = meter.Int64ObservableGauge(
		"dice.last.rolls",
		metric.WithDescription("The most recent rolled value"),
	)
	if err != nil {
		panic(err)
	}

	// Register the gauge callback.
	_, err = meter.RegisterCallback(
		func(_ context.Context, o metric.Observer) error {
			o.ObserveInt64(lastRollsGauge, lastRolls.Load())
			return nil
		},
		lastRollsGauge,
	)
	if err != nil {
		panic(err)
	}
}

func rollDice(ctx context.Context, rolls int) ([]int, error) {
	const maxRolls = 1000 // Arbitrary limit to prevent Slice memory allocation with excessive size value.

	ctx, span := tracer.Start(ctx, "rollDice")
	defer span.End()

	rollsAttr := attribute.Int("rolls", rolls)
	span.SetAttributes(rollsAttr)

	if rolls > maxRolls {
		err := errors.New("rolls parameter exceeds maximum allowed value")
		span.RecordError(err) //nolint:forbidigo // RecordError is used here to demonstrate error recording in spans as required by the specification.
		span.SetStatus(codes.Error, err.Error())
		return nil, err
	}

	if rolls <= 0 {
		err := errors.New("rolls must be positive")
		span.RecordError(err) //nolint:forbidigo // RecordError is used here to demonstrate error recording in spans as required by the specification.
		span.SetStatus(codes.Error, err.Error())
		return nil, err
	}

	results := make([]int, rolls)
	for i := range results {
		results[i] = rollOnce(ctx)
		outcomeHist.Record(ctx, int64(results[i]))
	}

	rollCnt.Add(ctx, int64(rolls), metric.WithAttributes(rollsAttr))
	lastRolls.Store(int64(rolls))
	return results, nil
}

// rollOnce returns a random number between 1 and 6.
func rollOnce(ctx context.Context) int {
	_, span := tracer.Start(ctx, "rollOnce")
	defer span.End()

	roll := 1 + rand.IntN(6) //nolint:gosec // G404: Use of weak random number generator (math/rand instead of crypto/rand) is ignored as this is not security-sensitive.

	rollValueAttr := attribute.Int("roll.value", roll)
	span.SetAttributes(rollValueAttr)

	return roll
}

Note that if you’re only using tracing or metrics, you can omit the corresponding code that instruments the other telemetry type.

Run the Application

Build and run the application with the following command:

go mod tidy
export OTEL_RESOURCE_ATTRIBUTES="service.name=dice,service.version=0.1.0"
go run .

Open http://localhost:8080/rolldice?player=Alice&rolls=3 in your browser. The console shows an HTTP server span, a child span named rollDice, and one rollOnce span per die. The application emits a DEBUG log record with the player name and roll results, and an INFO log record with the request method, path, and status code.

After the next metrics export, you’ll see the dice.rolls counter with the number of dice rolled, the dice.outcome histogram with the distribution of individual results, and the dice.last.rolls gauge with the number of dice in the most recent roll. The HTTP instrumentation also records request metrics.

View selected fields from the console output

One rollOnce span with the value of the die:

{
  "Name": "rollOnce",
  "Attributes": [{ "roll.value": 2 }]
}

The DEBUG log record with the player name and roll results:

{
  "SeverityText": "DEBUG",
  "Body": "player rolled dice",
  "Attributes": [{ "player": "Alice" }, { "results": [1, 1, 2] }]
}

The INFO log record for the request:

{
  "SeverityText": "INFO",
  "Body": "Some player rolled a dice.",
  "Attributes": [
    { "method": "GET" },
    { "path": "/rolldice" },
    { "status": 200 }
  ]
}

The dice.rolls counter after one request for three dice:

{
  "Name": "dice.rolls",
  "Unit": "{roll}",
  "Data": {
    "Temporality": "CumulativeTemporality",
    "IsMonotonic": true,
    "DataPoints": [{ "Attributes": { "rolls": 3 }, "Value": 3 }]
  }
}

Next steps

For more information about instrumenting your code, refer the manual instrumentation documentation.

You’ll also want to configure an appropriate exporter to export your telemetry data to one or more telemetry backends.

If you’d like to explore a more complex example, take a look at the OpenTelemetry Demo, which includes the Go-based Checkout Service and Product Catalog Service.