feat: add trace.SpanIDFromContext and trace.TraceIDFromContext (#2654)
parent
10fd9131a1
commit
9941055eaa
@ -0,0 +1,25 @@
|
||||
package trace
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
func SpanIDFromContext(ctx context.Context) string {
|
||||
spanCtx := trace.SpanContextFromContext(ctx)
|
||||
if spanCtx.HasSpanID() {
|
||||
return spanCtx.SpanID().String()
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func TraceIDFromContext(ctx context.Context) string {
|
||||
spanCtx := trace.SpanContextFromContext(ctx)
|
||||
if spanCtx.HasTraceID() {
|
||||
return spanCtx.TraceID().String()
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
@ -0,0 +1,32 @@
|
||||
package trace
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.4.0"
|
||||
oteltrace "go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
func TestSpanIDFromContext(t *testing.T) {
|
||||
tracer := sdktrace.NewTracerProvider().Tracer("test")
|
||||
ctx, span := tracer.Start(
|
||||
context.Background(),
|
||||
"foo",
|
||||
oteltrace.WithSpanKind(oteltrace.SpanKindClient),
|
||||
oteltrace.WithAttributes(semconv.HTTPClientAttributesFromHTTPRequest(httptest.NewRequest(http.MethodGet, "/", nil))...),
|
||||
)
|
||||
defer span.End()
|
||||
|
||||
assert.NotEmpty(t, TraceIDFromContext(ctx))
|
||||
assert.NotEmpty(t, SpanIDFromContext(ctx))
|
||||
}
|
||||
|
||||
func TestSpanIDFromContextEmpty(t *testing.T) {
|
||||
assert.Empty(t, TraceIDFromContext(context.Background()))
|
||||
assert.Empty(t, SpanIDFromContext(context.Background()))
|
||||
}
|
Loading…
Reference in New Issue