Integrations
Go

Go

Instrument Go applications with OpenTelemetry SDK and exporters.

Overview

Go applications require manual instrumentation with OpenTelemetry. The Go SDK provides a powerful and flexible API for adding traces, metrics, and logs to your applications.

Install

Add the OpenTelemetry Go SDK and OTLP exporter to your project:

go get go.opentelemetry.io/otel
go get go.opentelemetry.io/otel/sdk
go get go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp
go get go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp

Configure

1. Set environment variables

export OTEL_SERVICE_NAME="my-go-service"
export OTEL_EXPORTER_OTLP_ENDPOINT="https://ingress.us-east-2.rocketgraph.app"
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer YOUR_ROCKETLOGS_API_TOKEN"

2. Initialize OpenTelemetry in your application

package main

import (
    "context"
    "log"

    "go.opentelemetry.io/otel"
    "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
    "go.opentelemetry.io/otel/sdk/resource"
    sdktrace "go.opentelemetry.io/otel/sdk/trace"
    semconv "go.opentelemetry.io/otel/semconv/v1.21.0"
)

func initTracer() (*sdktrace.TracerProvider, error) {
    ctx := context.Background()
    
    exporter, err := otlptracehttp.New(ctx)
    if err != nil {
        return nil, err
    }

    tp := sdktrace.NewTracerProvider(
        sdktrace.WithBatcher(exporter),
        sdktrace.WithResource(resource.NewWithAttributes(
            semconv.SchemaURL,
            semconv.ServiceNameKey.String("my-go-service"),
        )),
    )
    
    otel.SetTracerProvider(tp)
    return tp, nil
}

func main() {
    tp, err := initTracer()
    if err != nil {
        log.Fatal(err)
    }
    defer tp.Shutdown(context.Background())

    // Your application code here
}

3. Create spans in your code

tracer := otel.Tracer("my-service")

ctx, span := tracer.Start(ctx, "my-operation")
defer span.End()

// Add attributes
span.SetAttributes(
    attribute.String("user.id", userID),
    attribute.Int("items.count", len(items)),
)

// Record errors
if err != nil {
    span.RecordError(err)
    span.SetStatus(codes.Error, err.Error())
}

Instrumentation Libraries

Use instrumentation libraries for common frameworks:

# HTTP server instrumentation (net/http)
go get go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp

# gRPC instrumentation
go get go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc

# SQL instrumentation
go get github.com/XSAM/otelsql

See the full list at OpenTelemetry Registry