Featured image of post OpenTelemetry

OpenTelemetry

Init otlp rpc

1
import "github.com/gogf/gf/contrib/trace/otlpgrpc/v2"
1
2
3
4
5
6
// endpoint := "localhost:4317"
shutdown, err := otlpgrpc.Init(serviceName, endpoint, traceToken)
if err != nil {
    return err
}
defer shutdown()

Span

span

1
import "github.com/gogf/gf/v2/net/gtrace"
1
2
3
4
5
6
7
8
9
// func ...(...) (..., err error)
ctx, span := gtrace.NewSpan(ctx, spanName)
defer span.End()
span.SetAttributes(attribute.String("tag", tag))
defer func() {
    if err != nil {
        span.SetStatus(codes.Error, err.Error())
    }
}()

event / log

1
2
3
span.AddEvent(name, trace.WithAttributes(
    attribute.String("tag", tag),
))

Inject / Extract

1
import "go.opentelemetry.io/otel"

Inject

Header

1
2
// req *http.Request
otel.GetTextMapPropagator().Inject(ctx, propagation.HeaderCarrier(req.Header))

Map

1
2
header := make(map[string]string)
otel.GetTextMapPropagator().Inject(ctx, propagation.MapCarrier(header))

Extract

1
2
// r *http.Request
ctx = otel.GetTextMapPropagator().Extract(ctx, propagation.HeaderCarrier(r.Header))

Jaeger

Docker

1
2
3
4
5
6
7
8
9
docker run -d \
    --name jaeger \
    -m 2g \
    -e COLLECTOR_OTLP_ENABLED=true \
    -p 16686:16686 \
    -p 4317:4317 \
    -p 4318:4318 \
    --restart unless-stopped \
    jaegertracing/all-in-one:1.60
Licensed under CC BY-NC-SA 4.0