OpenTelemetry for Go | Honeycomb

We use cookies or similar technologies to personalize your online experience & tailor marketing to you. Many of our product features require cookies to function properly.

Read our privacy policy I accept cookies from this site

OpenTelemetry for Go [Beta]

Honeycomb has an OpenTelemetry Distribution for Go that wraps the official OpenTelemetry Go SDK. It simplifies the setup process and lets you add instrumentation to your applications and send telemetry data to Honeycomb.

Requirements 

These instructions will explain how to set up automatic and manual instrumentation for a service written in Go. In order to follow along, you will need:

  • Go 1.14 or higher
  • An application written in Go
  • A Honeycomb API Key. You can find your API key in your Environment Settings. If you do not have an API key yet, sign up for a free Honeycomb account.

Examples 

There is an example that configures an application to send OpenTelemetry data to Honeycomb.

Automatic Instrumentation 

Acquire Dependencies 

Install the Honeycomb OpenTelemetry Go Distribution package:

go get github.com/honeycombio/honeycomb-opentelemetry-go \
  go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp

Initialize 

Configure your application to send spans to Honeycomb.

Open or create a file called main.go:

package main

import (
    "fmt"
    "log"
    "net/http"

    // NOTE: this import is super important as applies the Honeycomb
    // configuration to the launcher
    _ "github.com/honeycombio/honeycomb-opentelemetry-go"
    "github.com/honeycombio/opentelemetry-go-contrib/launcher"

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

// Implement an HTTP Handler func to be instrumented
func httpHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, World")
}

// Wrap the HTTP handler func with OTel HTTP instrumentation
func wrapHandler() {
    handler := http.HandlerFunc(httpHandler)
    wrappedHandler := otelhttp.NewHandler(handler, "hello")
    http.Handle("/hello", wrappedHandler)
}

func main() {
    // use honeycomb distro to setup OpenTelemetry SDK
    otelShutdown, err := launcher.ConfigureOpenTelemetry()
    if err != nil {
        log.Fatalf("error setting up OTel SDK - %e", err)
    }
    defer otelShutdown()

    // Initialize HTTP handler instrumentation
    wrapHandler()
    log.Fatal(http.ListenAndServe(":3030", nil))
}

Configure and Run 

Configure the Honeycomb Distribution for Go using environment variables.

Your service name will be used as the Service Dataset in Honeycomb, which is where data is stored. The service name is specified by OTEL_SERVICE_NAME.

export OTEL_SERVICE_NAME="your-service-name"
export HONEYCOMB_API_KEY="your-api-key"

Now you can run your application and see traces created for each incoming HTTP request:

go run main.go

If you are a Honeycomb Classic user, the Dataset also must be specified using the HONEYCOMB_DATASET environment variable. A Dataset is a bucket where data gets stored in Honeycomb.

export HONEYCOMB_DATASET="your-dataset"

Using HTTP/protobuf instead of gRPC 

To use HTTP instead of gRPC, set the OTEL_EXPORTER_OTLP_PROTOCOL environment variable:

export OTEL_EXPORTER_OTLP_PROTOCOL="http/protobuf"

Adding Manual Instrumentation 

Adding Attributes to Spans 

It is often beneficial to add context to a currently executing span in a trace. For example, you may have an application or service that handles users, and you want to associate the user with the span when querying your dataset in Honeycomb. In order to do this, get the current span from the context and set an attribute with the user ID. This example assumes you are writing a web application with the net/http package:

import (
  // ...
  "go.opentelemetry.io/otel/attribute"
  "go.opentelemetry.io/otel/trace"
  // ...
)

// ...
handler := func(w http.ResponseWriter, r *http.Request) {
  user := someServiceCall() // get the currently logged in user
  ctx := r.Context()
  span := trace.SpanFromContext(ctx)
  span.SetAttributes(attribute.Int("user.id", user.getID()))
}
// ...

This will add a user.id field to the current span so that you can use the field in WHERE, GROUP BY, or ORDER clauses in the Honeycomb query builder.

Creating Spans 

Auto-instrumentation can show the shape of requests to your system, but only you know the really important parts. In order to get the full picture of what is happening, you will have to add manual instrumentation and create some custom spans. To do this, grab the tracer from the OpenTelemetry API:

import (
  // ...
  "go.opentelemetry.io/otel"
  // ...
)

// ...
tracer := otel.Tracer("my-app") // if not already in scope
ctx, span := tracer.Start(ctx, "expensive-operation")
defer span.End()
// ...

More on Manual Instrumentation 

The OpenTelemetry documentation for Go has a comprehensive set of topics on manual instrumentation.

Sampling 

Honeycomb’s OpenTelemetry Distribution for Go includes a sampler that can be configured to use a Honeycomb sample rate. To configure the sampler, set the HONEYCOMB_SAMPLE_RATE environment variable:

export HONEYCOMB_SAMPLE_RATE=2

If you have multiple services that communicate with each other, it is important that they have the same sampling configuration. Otherwise, each service might make a different sampling decision, resulting in incomplete or broken traces. You can sample using a standalone proxy as an alternative, like Honeycomb Refinery, or when you have more robust sampling needs.

Distributed Trace Propagation 

When a service calls another service, you want to ensure that the relevant trace information is propagated from one service to the other. This allows Honeycomb to connect the two services in a trace.

Distributed tracing enables you to trace and visualize interactions between multiple instrumented services. For example, your users may interact with a front-end API service, which talks to two internal APIs to fulfill their request. In order to have traces connect spans for all these services, it is necessary to propagate trace context between these services, usually by using an HTTP header.

Both the sending and receiving service must use the same propagation format, and both services must be configured to send data to the same Honeycomb dataset.

Note: Any Baggage attributes that you set in your application will be attached to outgoing network requests as a header. If your service communicates to a third party API, do NOT put sensitive information in the Baggage attributes.

Trace context propagation is done by sending and parsing headers that conform to the W3C Trace Context specification.

By default, the Honeycomb’s OpenTelemetry Distribution for Go uses the W3C trace context format.

If you opt to use a different trace context specification than W3C, you will need to ensure that both the sending and receiving service must be using the same propagation format, and both services must be configured to send data to the same Honeycomb dataset.

Visualize Traces Locally 

Honeycomb’s OpenTelemetry Distribution for Go can create a link to a trace visualization in the Honeycomb UI for local traces. Local visualizations enables a faster feedback cycle when adding, modifying, or verifying instrumentation.

To enable local visualizations, set the HONEYCOMB_ENABLE_LOCAL_VISUALIZATIONS environment variable to true:

export HONEYCOMB_ENABLE_LOCAL_VISUALIZATIONS=true

Then, run your application:

go run main.go

The output displays the name of the root span and a link to Honeycomb that shows its trace. For example:

Trace for root-span-name
Honeycomb link: <link to Honeycomb trace>

In production, disable local visualization as it creates additional overhead to create the link and print it to the console.

Using OpenTelemetry Without the Honeycomb Distribution 

The primary purpose of Honeycomb’s Distribution for Go is to streamline configuration and to instrument as quickly and easily as possible. Under the hood, the Honeycomb Distribution is using OpenTelemetry for Go, which means OpenTelemetry can be used with or without this Distribution. It may be unnecessary for advanced users or those already instrumented with OpenTelemetry to use the Distribution.

The Honeycomb Distribution reads specific variables and translates them to variables understood by upstream OpenTelemetry SDK. For example, the distribution automatically configures exporters to send telemetry data to Honeycomb’s API api.honeycomb.io. Therefore, to send data to Honeycomb using OpenTelemetry without the Distribution, a different configuration is necessary to match expected variables.

Follow the directions below to instrument with OpenTelemetry for Go.

Install Packages 

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

Configure Environment Variables 

export OTEL_SERVICE_NAME="your-service-name"
export OTEL_EXPORTER_OTLP_ENDPOINT="api.honeycomb.io:443"
export OTEL_EXPORTER_OTLP_HEADERS="x-honeycomb-team=your-api-key"

Run 

package main

import (
  "context"
  "fmt"
  "log"
  "net/http"

  "go.opentelemetry.io/otel"
  "go.opentelemetry.io/otel/exporters/otlp/otlptrace"
  "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
  "go.opentelemetry.io/otel/propagation"
  "go.opentelemetry.io/otel/sdk/trace"

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

func main() {
  ctx := context.Background()

  // Configure a new OTLP exporter using environment variables for sending data to Honeycomb over gRPC
  client := otlptracegrpc.NewClient()
  exp, err := otlptrace.New(ctx, client)
  if err != nil {
    log.Fatalf("failed to initialize exporter: %e", err)
  }

  // Create a new tracer provider with a batch span processor and the otlp exporter
  tp := trace.NewTracerProvider(
    trace.WithBatcher(exp),
  )

  // Handle shutdown to ensure all sub processes are closed correctly and telemetry is exported
  defer func() {
    _ = exp.Shutdown(ctx)
    _ = tp.Shutdown(ctx)
  }()

  // Register the global Tracer provider
  otel.SetTracerProvider(tp)

  // Register the W3C trace context and baggage propagators so data is propagated across services/processes
  otel.SetTextMapPropagator(
    propagation.NewCompositeTextMapPropagator(
      propagation.TraceContext{},
      propagation.Baggage{},
    ),
  )

  // Implement an HTTP handler func to be instrumented
  handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, World")
  })

  // Setup handler instrumentation
  wrappedHandler := otelhttp.NewHandler(handler, "hello")
  http.Handle("/hello", wrappedHandler)

  // Start web server
  log.Fatal(http.ListenAndServe(":3030", nil))
}

If you are a Honeycomb Classic user, the Dataset also must be specified using the HONEYCOMB_DATASET environment variable. A Dataset is a bucket where data gets stored in Honeycomb.

export OTEL_EXPORTER_OTLP_HEADERS="x-honeycomb-team=your-api-key,x-honeycomb-dataset=your-dataset"

Endpoint URLs for OTLP/HTTP 

When using the OTEL_EXPORTER_OTLP_ENDPOINT environment variable with an SDK and an HTTP exporter, the final path of the endpoint is actually modified by the SDK to represent the specific signal being sent.

For example, when exporting trace data, the endpoint is updated to append v1/traces. When exporting metrics data, the endpoint is updated to append v1/metrics. The same modification is not necessary for gRPC.

By setting OTEL_EXPORTER_OTLP_ENDPOINT to https://api.honeycomb.io, traces are sent to https://api.honeycomb.io/v1/traces and metrics to https://api.honeycomb.io/v1/metrics.

export OTEL_EXPORTER_OTLP_ENDPOINT=https://api.honeycomb.io

If the desired outcome is to send data to a different endpoint depending on the signal, use OTEL_EXPORTER_OTLP_<SIGNAL>_ENDPOINT instead of the more generic OTEL_EXPORTER_OTLP_ENDPOINT.

When using a signal-specific environment variable, these paths must be appended manually. Set OTEL_EXPORTER_OTLP_TRACES_ENDPOINT for traces, appending the endpoint with v1/traces, and OTEL_EXPORTER_OTLP_METRICS_ENDPOINT for metrics, appending the endpoint with v1/metrics.

Send both traces and metrics to Honeycomb using this method by setting the following variables:

export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://api.honeycomb.io/v1/traces
export OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=https://api.honeycomb.io/v1/metrics

More details about endpoints and signals can be found in the OpenTelemetry Specification.

Troubleshooting 

No Traces for a Service 

The service name is a required configuration value. If it is unspecified, all trace data will be sent to a default dataset called unknown_service.

Printing to the Console 

If no errors appear but your data is not in Honeycomb as expected, you can set the DEBUG environment variable, which will both log the distribution configuration to stdout and configure spans to be output to stdout. This will help confirm whether your app is being instrumented with the data you expect.

export DEBUG=true

Keep in mind that printing to the console should only be used for debugging purposes. It is not recommended for production.

OTLP Protobuf Definitions 

Honeycomb supports receiving telemetry data via OpenTelemetry’s native protocol, OTLP, over gRPC, HTTP/protobuf, and HTTP/JSON. The minimum supported versions of OTLP protobuf definitions are 0.7.0 for traces and metrics.

If the protobuf version in use by the SDK does not match a supported version by Honeycomb, a different version of the SDK may need to be used. If the SDK’s protobuf version is older than the minimum supported version, and telemetry is not appearing as expected in Honeycomb, upgrade the SDK to a version with the supported protobuf definitions. If using an added dependency on a proto library, ensure the version of protobuf definitions matches the supported version of the SDK.

Receiving 464 Errors 

You may receive a 464 error response from the Honeycomb API when sending telemetry using gRPC and HTTP1. The gRPC format depends on using HTTP2 and any request over HTTP1 will be rejected by the Honeycomb servers.

Did you find what you were looking for?