We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Instrumenting Traces

To begin sending traces to Jaeger, we need to add instrumentation to our application. The first step is to add several dependencies:

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

With these imports in place, we're now ready to initialize the OpenTelemetry exporter in our application.

import (
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
	"go.opentelemetry.io/otel/sdk/resource"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
)

func initTracing(ctx context.Context) (func(context.Context) error, error) {
	exp, err := otlptracegrpc.New(ctx)
	if err != nil {
		return nil, err
	}

	tp := sdktrace.NewTracerProvider(
		sdktrace.WithBatcher(exp,
			sdktrace.WithBatchTimeout(2*time.Second),
		),
		sdktrace.WithResource(resource.Default()),
	)

	otel.SetTracerProvider(tp)
	return tp.Shutdown, nil
}

By default, the OTLP/gRPC exporter targets localhost:4317 using TLS. We'll disable TLS for local development and set the service name to linko with environment variables.

With the tracing pipeline in place, we can now begin tracing using the middleware function in go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp:

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

func main() {
	// ...
	mux := http.NewServeMux()
	// ... Existing routes setup
	h := otelhttp.NewHandler(mux, "http.server") // <-- this is the magic!
	http.ListenAndServe(":8080", h)
}

By using otelhttp.NewHandler to wrap your root handler, you get:

  1. A trace for each inbound request by creating a root span.
  2. A root span injected into the request context, so downstream function calls can access it.

Assignment

  1. OTEL_EXPORTER_OTLP_TRACES_INSECURE=true OTEL_SERVICE_NAME=linko go run .
    

Run and submit the CLI tests from the root of the Linko repo.