Go
Instrument your Go app using openTelemetry and export traces to Aspecto's collector.
​

Install OpenTelemetry SDK

1
go get go.opentelemetry.io/[email protected] \
2
go.opentelemetry.io/otel/[email protected] \
3
go.opentelemetry.io/otel/[email protected] \
4
go.opentelemetry.io/otel/sdk/resource \
5
go.opentelemetry.io/otel/propagation \
6
go.opentelemetry.io/otel/semconv/v1.4.0 \
7
go.opentelemetry.io/otel/exporters/otlp/otlptrace/[email protected]
Copied!

Initialize OpenTelemetry

add to your main.go file the following imports
1
import (
2
"go.opentelemetry.io/otel"
3
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
4
"go.opentelemetry.io/otel/propagation"
5
"go.opentelemetry.io/otel/sdk/resource"
6
sdktrace "go.opentelemetry.io/otel/sdk/trace"
7
semconv "go.opentelemetry.io/otel/semconv/v1.4.0"
8
)
Copied!
and then in your main function add the following code
1
ctx := context.Background()
2
traceExporter, err := otlptracehttp.New(ctx,
3
otlptracehttp.WithEndpoint("otelcol.aspecto.io"),
4
otlptracehttp.WithHeaders(map[string]string{"Authorization": "<YOUR ASPECTO TOKEN HERE>"}))
5
​
6
if err != nil {
7
log.Fatal(err)
8
}
9
​
10
res, err := resource.New(ctx,
11
resource.WithAttributes(
12
semconv.ServiceNameKey.String("<YOUR SERVICE NAME>"),
13
),
14
)
15
​
16
if err != nil {
17
log.Fatal(err)
18
}
19
​
20
tp := sdktrace.NewTracerProvider(
21
sdktrace.WithSampler(sdktrace.AlwaysSample()),
22
sdktrace.WithResource(res),
23
sdktrace.WithBatcher(traceExporter))
24
otel.SetTracerProvider(tp)
25
otel.SetTextMapPropagator(propagation.TraceContext{})
Copied!

Auto Instrumentation

Go has support for a few popular libraries including net/http go-redis and mongo-driver

net/http

go get go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp
you will need to wrap each http handler with otelHandler see an example below
1
handler := func(w http.ResponseWriter, req *http.Request) {
2
//your handler code
3
}
4
​
5
http.Handle("/hello", otelhttp.NewHandler(http.HandlerFunc(handler), "Handler"))
Copied!

go-redis

go get github.com/go-redis/redis/extra/redisotel/v8
then add the following code to your redis client initialization code
1
import (
2
"github.com/go-redis/redis/v8"
3
"github.com/go-redis/redis/extra/redisotel"
4
)
5
​
6
rdb := rdb.NewClient(&rdb.Options{...})
7
​
8
rdb.AddHook(redisotel.NewTracingHook())
Copied!

mongo-driver

go get go.opentelemetry.io/contrib/instrumentation/go.mongodb.org/mongo-driver/mongo/otelmongo
then add the following code to your mongo client initialization code
1
opts := options.Client()
2
opts.Monitor = otelmongo.NewMonitor()
Copied!
You can find the full list of instrumentations here​
Last modified 14d ago