opentelemetry golang always give all 0 for traceID and spanID

Viewed 28

I am totally new to the distributed world and trying to use open telemetry for distributed tracing. For phase 1, just trying to have a request id (traceID / spanID) going, so we can co-relate the request logs. Have not yet decided on collector/ exporter.

My span/ trace id is always zero, in below middleware code Is it because I have not initialized the tracer with all the exporter/ collector etc?


func AddSpanId(h http.Handler) http.Handler {
    fn := func(w http.ResponseWriter, r *http.Request) {
        values := []interface{}{}
        spanID, traceID := getRequestIDs(r)
        values = append(values, "spanID", spanID)
        values = append(values, "traceID", traceID)
        
        //code to wrap values into context
}

func getRequestIDs(r *http.Request) (string, string) {
    _, span := otel.Tracer("somename").Start(r.Context(), "handler")
    fmt.Print(span.SpanContext().SpanID().String())
    return span.SpanContext().SpanID().String(), span.SpanContext().TraceID().String()
} 
1 Answers

You need to instrument your http handler:

import (
    "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
    "go.opentelemetry.io/otel"
    "go.opentelemetry.io/otel/attribute"
)

// Package-level tracer.
// This should be configured in your code setup instead of here.
var tracer = otel.Tracer("github.com/full/path/to/mypkg")


func main() {
    // Wrap your httpHandler function.
    handler := http.HandlerFunc(httpHandler)
    wrappedHandler := otelhttp.NewHandler(handler, "hello-instrumented")
    http.Handle("/hello-instrumented", wrappedHandler)

    // And start the HTTP serve.
    log.Fatal(http.ListenAndServe(":3030", nil))
}

https://opentelemetry.io/docs/instrumentation/go/libraries/

You also rarely need to work directly with traceID and spanID. Starting Span API is typical building block to instrument the code.

_, span := otel.Tracer(name).Start(ctx, "Poll")
defer span.End() 
Related