OpenTelemetry
- Go course
- Advanced
- Lesson 62/68
- 4 min
Learn the basics of the OpenTelemetry SDK in Go.
OpenTelemetry
OpenTelemetry (OTel) is an open standard for collecting traces, metrics and logs in a vendor-neutral way. You write code once against the OTel API; data is sent with an exporter to any backend such as Jaeger, Grafana Tempo or Datadog.
tracer := otel.Tracer("siparis-servisi")
ctx, span := tracer.Start(ctx, "SiparisOlustur")
defer span.End()
span.SetAttributes(attribute.Int("urun_sayisi", 3))SDK setup and auto-instrumentation
At program start a TracerProvider is set up and made global; on exit Shutdown flushes buffered spans. Ready-made packages such as otelhttp trace HTTP servers and clients automatically:
handler := otelhttp.NewHandler(mux, "api")
client := http.Client{Transport: otelhttp.NewTransport(http.DefaultTransport)}This way opening a span per request and carrying the traceparent header happen on their own.
Practice Span with attributes
Build an OTel-like structure: type Span struct { Ad string; Attr map[string]any } and func (s *Span) Set(k string, v any). Create a span, add "urun_sayisi" = 3 and "odeme" = "kart", and print len(s.Attr).
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
type Span struct {
Ad string
Attr map[string]any
}
func (s *Span) Set(k string, v any) {
if s.Attr == nil {
s.Attr = map[string]any{}
}
s.Attr[k] = v
}
func main() {
s := &Span{Ad: "SiparisOlustur"}
s.Set("urun_sayisi", 3)
s.Set("odeme", "kart")
fmt.Println(len(s.Attr))
}Expected output
2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What changes when switching the backend from Jaeger to Tempo?
- The Go version
- The database
- Only the exporter setup Correct answer
- All span code
Explanation: Application code depends on the OTel API; the backend difference stays in the SDK setup's exporter.
2 Add an attribute
span.____(attribute.String("kullanici", id))
span.SetAttributes(attribute.String("kullanici", id))
Explanation: SetAttributes adds queryable key-value information to a span.
3 OTel parts
| Term | Meaning |
|---|---|
API |
Interface the code uses |
SDK |
Sampling and processing |
Exporter |
Sends to the backend |
otelhttp |
Automatic HTTP tracing |