context.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. package trace // import "go.opentelemetry.io/otel/trace"
  4. import "context"
  5. type traceContextKeyType int
  6. const currentSpanKey traceContextKeyType = iota
  7. // ContextWithSpan returns a copy of parent with span set as the current Span.
  8. func ContextWithSpan(parent context.Context, span Span) context.Context {
  9. return context.WithValue(parent, currentSpanKey, span)
  10. }
  11. // ContextWithSpanContext returns a copy of parent with sc as the current
  12. // Span. The Span implementation that wraps sc is non-recording and performs
  13. // no operations other than to return sc as the SpanContext from the
  14. // SpanContext method.
  15. func ContextWithSpanContext(parent context.Context, sc SpanContext) context.Context {
  16. return ContextWithSpan(parent, nonRecordingSpan{sc: sc})
  17. }
  18. // ContextWithRemoteSpanContext returns a copy of parent with rsc set explicitly
  19. // as a remote SpanContext and as the current Span. The Span implementation
  20. // that wraps rsc is non-recording and performs no operations other than to
  21. // return rsc as the SpanContext from the SpanContext method.
  22. func ContextWithRemoteSpanContext(parent context.Context, rsc SpanContext) context.Context {
  23. return ContextWithSpanContext(parent, rsc.WithRemote(true))
  24. }
  25. // SpanFromContext returns the current Span from ctx.
  26. //
  27. // If no Span is currently set in ctx an implementation of a Span that
  28. // performs no operations is returned.
  29. func SpanFromContext(ctx context.Context) Span {
  30. if ctx == nil {
  31. return noopSpanInstance
  32. }
  33. if span, ok := ctx.Value(currentSpanKey).(Span); ok {
  34. return span
  35. }
  36. return noopSpanInstance
  37. }
  38. // SpanContextFromContext returns the current Span's SpanContext.
  39. func SpanContextFromContext(ctx context.Context) SpanContext {
  40. return SpanFromContext(ctx).SpanContext()
  41. }