Skip to content

Commit

Permalink
API: create new linked span from current context (#2115)
Browse files Browse the repository at this point in the history
* API: create new linked span from current context

* ran make precommit

* Update trace/trace.go

* Updated CHANGELOG

Co-authored-by: Tyler Yahn <[email protected]>
  • Loading branch information
bhautikpip and MrAlias authored Jul 22, 2021
1 parent db81d4a commit abe2243
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
8 changes: 8 additions & 0 deletions trace/trace.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
18 changes: 18 additions & 0 deletions trace/trace_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand Down Expand Up @@ -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)
}

0 comments on commit abe2243

Please sign in to comment.