Skip to Content
Xeonr Developer Docs

Go

Send traces, metrics and logs from a Go server, worker or CLI to Lantern with OpenTelemetry-Go and OTLP/HTTP, and choose between logging to stdout and exporting logs.

A Go program sends to Lantern with the standard OpenTelemetry-Go SDK. Set it up once in main, and everything instrumented with OpenTelemetry reports through it: your own spans, net/http, gRPC, Connect, database drivers.

Lantern's add-on, git.prod.wtf/xeonr/lantern/otel/go, does that setup in one call. It doesn't replace the SDK: it builds the stock providers and otlp*http exporters and adds Lantern's endpoint, credential and resource attributes. Without it, the stock SDK reads the same things from OTEL_* variables (below).

Before you start

  • Go 1.26 or newer, which OpenTelemetry-Go 1.47 requires. With Go's default GOTOOLCHAIN=auto, an older go command fetches 1.26 by itself.
  • An edge credential for your organisation (see Server telemetry).

Checked with OpenTelemetry-Go 1.47.0 (otlploghttp 0.23.0, otelslog 0.21.0, otelhttp 0.72.0) and git.prod.wtf/xeonr/lantern/otel/go v0.1.0.

Already on OpenTelemetry? Add this

go get git.prod.wtf/xeonr/lantern/otel/go

Replace the code in main that builds the providers and exporters:

main.go
import lntrn "git.prod.wtf/xeonr/lantern/otel/go"

tel, err := lntrn.Setup(ctx, lntrn.Options{ServiceName: "checkout-api", ServiceVersion: version})
if err != nil {
	return err
}
defer tel.Shutdown(context.Background()) // flushes the last batch; give it a timeout in a server

slog.SetDefault(tel.Logger("checkout-api")) // slog as OTLP logs, carrying the active span
export LNTRN_EDGE_USER=<org>.<id>       # the edge credential's username
export LNTRN_EDGE_PASSWORD=…            # and its password
export LNTRN_NAMESPACE=checkout LNTRN_ENVIRONMENT=prod

What lntrn.Setup does:

  • Providers: it builds the stock sdktrace, sdkmetric and sdklog providers, each with its otlp*http exporter to https://otlp.lntrn.dev and the credential as HTTP Basic.
  • Globals: it installs them, with the W3C trace-context and baggage propagators, so otel.Tracer(…), otelhttp and otelconnect report through them.
  • Resource: service.name, service.version, service.namespace and deployment.environment.name. OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES still win, as in every SDK.
  • Turning a signal off: OTEL_TRACES_EXPORTER, OTEL_METRICS_EXPORTER or OTEL_LOGS_EXPORTER set to none leaves that signal out.

It picks where to send from what is set:

SetSends to
LNTRN_EDGE_USER and LNTRN_EDGE_PASSWORDthe edge, https://otlp.lntrn.dev, with HTTP Basic
a device token (Options.Token or LNTRN_DEVICE_TOKEN)the client ingest, https://in.lntrn.dev (see Devices)
LNTRN_ENDPOINT alonethat endpoint, with no credential: an in-cluster collector
OTEL_EXPORTER_OTLP_ENDPOINTwherever the standard variables say
nothingnowhere. Spans still get ids, so log lines still carry them

LNTRN_ENDPOINT also replaces the edge's address. The examples below use a setupTelemetry of their own; with the add-on, call lntrn.Setup there instead.

Without the add-on

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/bridges/otelslog

Use the …http exporters. Lantern's edge is OTLP/HTTP only, so the …grpc ones cannot reach it.

Set up the SDK

One function installs a tracer, meter and logger provider, all exporting to the edge. Put it in telemetry.go:

telemetry.go
package main

import (
	"context"
	"errors"
	"time"

	"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"
	"go.opentelemetry.io/otel/sdk/resource"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
)

// setupTelemetry installs trace, metric and log providers that export
// OTLP/HTTP to the endpoint and headers in OTEL_EXPORTER_OTLP_*. The
// returned function flushes and stops them; call it before exiting.
func setupTelemetry(ctx context.Context) (func(context.Context) error, error) {
	// service.name, service.version and deployment.environment.name come
	// from OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES.
	res, err := resource.New(ctx, resource.WithFromEnv(), resource.WithTelemetrySDK(), resource.WithHost())
	if err != nil {
		return nil, err
	}

	traceExp, err := otlptracehttp.New(ctx)
	if err != nil {
		return nil, err
	}
	tp := sdktrace.NewTracerProvider(sdktrace.WithResource(res), sdktrace.WithBatcher(traceExp))
	otel.SetTracerProvider(tp)
	otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{}))

	metricExp, err := otlpmetrichttp.New(ctx)
	if err != nil {
		return nil, err
	}
	mp := sdkmetric.NewMeterProvider(sdkmetric.WithResource(res),
		sdkmetric.WithReader(sdkmetric.NewPeriodicReader(metricExp, sdkmetric.WithInterval(30*time.Second))))
	otel.SetMeterProvider(mp)

	logExp, err := otlploghttp.New(ctx)
	if err != nil {
		return nil, err
	}
	lp := sdklog.NewLoggerProvider(sdklog.WithResource(res), sdklog.WithProcessor(sdklog.NewBatchProcessor(logExp)))
	global.SetLoggerProvider(lp)

	return func(ctx context.Context) error {
		return errors.Join(tp.Shutdown(ctx), mp.Shutdown(ctx), lp.Shutdown(ctx))
	}, nil
}

With no options, each exporter reads OTEL_EXPORTER_OTLP_ENDPOINT, OTEL_EXPORTER_OTLP_HEADERS (the Basic credential) and the rest of the standard variables, and appends its own path. resource.WithFromEnv reads OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES, which carry the attributes every record should have (see Server telemetry).

A CLI or batch job

A short-lived program has to flush before it exits, or its last batch never leaves. Here a deferred shutdown does it, on success or failure:

main.go
package main

import (
	"context"
	"errors"
	"log/slog"
	"os"
	"time"

	"go.opentelemetry.io/contrib/bridges/otelslog"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/codes"
)

func main() {
	if err := run(); err != nil {
		os.Exit(1)
	}
}

func run() error {
	ctx := context.Background()
	shutdown, err := setupTelemetry(ctx)
	if err != nil {
		slog.Error("telemetry setup failed", "error", err)
		return err
	}
	// A CLI exits as soon as its work is done: flush before it does, or the
	// last batch is lost.
	defer func() {
		ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
		defer cancel()
		if err := shutdown(ctx); err != nil {
			slog.Error("telemetry shutdown failed", "error", err)
		}
	}()

	// slog through the OpenTelemetry bridge: every record is an OTLP log
	// carrying the active span's trace and span ids.
	logger := otelslog.NewLogger("import-cli")
	tracer := otel.Tracer("import-cli")
	imported, err := otel.Meter("import-cli").Int64Counter("import.records")
	if err != nil {
		return err
	}

	ctx, span := tracer.Start(ctx, "import")
	defer span.End()
	span.SetAttributes(attribute.Int("import.batch_size", 3))

	for i := range 3 {
		_, item := tracer.Start(ctx, "import-record")
		imported.Add(ctx, 1)
		logger.InfoContext(ctx, "record imported", "record", i)
		item.End()
	}

	err = errors.New("upstream timed out")
	span.RecordError(err)
	span.SetStatus(codes.Error, err.Error())
	logger.ErrorContext(ctx, "import failed", "error", err)
	return err
}

Run it with the credential and the resource attributes set:

export OTEL_SERVICE_NAME=import-cli
export OTEL_RESOURCE_ATTRIBUTES=service.namespace=imports,service.version=1.0.0,deployment.environment.name=dev
go run .

A server

For a long-running server, wrap the handler in otelhttp for one server span per request, and shut telemetry down after the server has drained:

go get go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp
main.go
package main

import (
	"context"
	"log/slog"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

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

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()

	shutdown, err := setupTelemetry(ctx)
	if err != nil {
		slog.Error("telemetry setup failed", "error", err)
		os.Exit(1)
	}
	logger := otelslog.NewLogger("checkout-api")

	mux := http.NewServeMux()
	mux.HandleFunc("GET /orders/{id}", func(w http.ResponseWriter, r *http.Request) {
		logger.InfoContext(r.Context(), "order fetched", "order.id", r.PathValue("id"))
		w.Write([]byte("ok\n"))
	})

	// One server span per request, named by the route pattern.
	srv := &http.Server{Addr: ":8080", Handler: otelhttp.NewHandler(mux, "http.server")}
	go func() {
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			logger.Error("server failed", "error", err)
			stop()
		}
	}()

	<-ctx.Done()
	shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	srv.Shutdown(shutdownCtx)
	shutdown(shutdownCtx) // after the server has drained: flushes the last spans and logs
}

Spans are named after the matched route pattern (GET /orders/{id}), so the service page groups requests by endpoint rather than by URL. Client calls made with otelhttp.NewTransport or a gRPC/Connect interceptor carry the trace on to the next service. For Connect, use otelconnect with otelconnect.WithTrustRemote() on servers that take calls from your other services. Without it, each service starts a new trace and links to the caller's, instead of continuing it.

Logs: stdout or OTLP

The examples above export logs over OTLP through the otelslog bridge, which is right for a CLI, a VM or anything else outside Kubernetes.

In a Kubernetes cluster running Lantern's agent, write JSON to stdout instead, and drop the log provider from setupTelemetry (with the add-on, set OTEL_LOGS_EXPORTER=none, and use lntrn.TraceHandler for the wrapper below). The agent reads every container's output, panics and stderr included, and links each line to its trace by its trace_id and span_id fields. slog's JSON handler writes the rest of the shape (time, level, msg); this wrapper adds the ids from the context:

// traceHandler adds the active span's trace_id and span_id to every record,
// so a log line on stdout links to its trace.
type traceHandler struct{ slog.Handler }

func (h traceHandler) Handle(ctx context.Context, r slog.Record) error {
	if sc := trace.SpanContextFromContext(ctx); sc.IsValid() {
		r.AddAttrs(slog.String("trace_id", sc.TraceID().String()), slog.String("span_id", sc.SpanID().String()))
	}
	return h.Handler.Handle(ctx, r)
}

func (h traceHandler) WithAttrs(as []slog.Attr) slog.Handler {
	return traceHandler{h.Handler.WithAttrs(as)}
}

func (h traceHandler) WithGroup(name string) slog.Handler {
	return traceHandler{h.Handler.WithGroup(name)}
}
slog.SetDefault(slog.New(traceHandler{slog.NewJSONHandler(os.Stdout, nil)}))

slog.InfoContext(ctx, "order fetched", "order.id", id)
// {"time":"…","level":"INFO","msg":"order fetched","order.id":"42","trace_id":"1b01…","span_id":"03f2…"}

Pass the request's context (InfoContext, ErrorContext) or the line has no trace to link to. Don't do both: a line written to stdout and exported over OTLP is stored twice.

Verify

Run the program, then within a minute:

lntrn --org <org> query traces 'service.name:import-cli' --since 15m
lntrn --org <org> query logs 'service.name:import-cli severity:error' --since 15m

Or open Traces in the console at https://<org>.lntrn.dev and filter by service.name. The error span and the import failed log line share a trace id, and the log line opens its trace.

If nothing arrives:

  • check the credential with the curl in Server telemetry;
  • set OTEL_LOG_LEVEL=debug to see the exporters' errors;
  • make sure the program reaches shutdown. An os.Exit skips deferred calls.

Devices

A program on hardware you don't control, such as a desktop app or a daemon on a customer's machine, shouldn't hold an edge credential. It sends to a client project with a short-lived device token instead (see Authentication). Give lntrn.Setup a function that fetches one:

tel, err := lntrn.Setup(ctx, lntrn.Options{
	ServiceName: "living-room-hub",
	Token: func(ctx context.Context) (string, error) {
		return myBackend.DeviceToken(ctx) // or lanterndevice.Mint(…) where the signing key lives
	},
})

How the token is cached:

  • the token is reused until shortly before its exp: a minute before, or at four fifths of a shorter lifetime;
  • concurrent exports share one fetch;
  • a 401 from the ingest drops the cached token, so the next export fetches a new one.

What the ingest stamps. It files the records under the token's project, whose service name and environment win over the resource. The token's client id becomes service.instance.id.

The Go device SDK (see Devices) is the other way, with a small log/metric/event API of its own.

On this page