diff --git a/CHANGELOG.md b/CHANGELOG.md index 00cc68b561f..6ebf2fcb081 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm - Added `WithOSDescription` resource configuration option to set OS (Operating System) description resource attribute (`os.description`). (#1840) - Added `WithOS` resource configuration option to set all OS (Operating System) resource attributes at once. (#1840) +- Added API `LinkFromContext` to return Link which encapsulates SpanContext from provided context and also encapsulates attributes. (#2115) ### Changed diff --git a/trace/trace.go b/trace/trace.go index 15eb4673b41..8564cb9dfe6 100644 --- a/trace/trace.go +++ b/trace/trace.go @@ -408,6 +408,14 @@ type Link struct { DroppedAttributeCount int } +// LinkFromContext returns a link encapsulating the SpanContext in the provided ctx. +func LinkFromContext(ctx context.Context, attrs ...attribute.KeyValue) Link { + return Link{ + SpanContext: SpanContextFromContext(ctx), + Attributes: attrs, + } +} + // SpanKind is the role a Span plays in a Trace. type SpanKind int diff --git a/trace/trace_test.go b/trace/trace_test.go index 2a32270b27b..d6115f286b9 100644 --- a/trace/trace_test.go +++ b/trace/trace_test.go @@ -16,8 +16,13 @@ package trace import ( "bytes" + "context" "testing" + "github.com/stretchr/testify/assert" + + "go.opentelemetry.io/otel/attribute" + "github.com/google/go-cmp/cmp" ) @@ -643,3 +648,16 @@ func TestSpanContextDerivation(t *testing.T) { t.Fatalf("WithTraceState: Unexpected context created: %s", cmp.Diff(modified, to)) } } + +func TestLinkFromContext(t *testing.T) { + k1v1 := attribute.String("key1", "value1") + spanCtx := SpanContext{traceID: TraceID([16]byte{1}), remote: true} + + receiverCtx := ContextWithRemoteSpanContext(context.Background(), spanCtx) + link := LinkFromContext(receiverCtx, k1v1) + + if !assertSpanContextEqual(link.SpanContext, spanCtx) { + t.Fatalf("LinkFromContext: Unexpected context created: %s", cmp.Diff(link.SpanContext, spanCtx)) + } + assert.Equal(t, link.Attributes[0], k1v1) +}