context.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright The OpenTelemetry Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package trace // import "go.opentelemetry.io/otel/trace"
  15. import "context"
  16. type traceContextKeyType int
  17. const currentSpanKey traceContextKeyType = iota
  18. // ContextWithSpan returns a copy of parent with span set as the current Span.
  19. func ContextWithSpan(parent context.Context, span Span) context.Context {
  20. return context.WithValue(parent, currentSpanKey, span)
  21. }
  22. // ContextWithSpanContext returns a copy of parent with sc as the current
  23. // Span. The Span implementation that wraps sc is non-recording and performs
  24. // no operations other than to return sc as the SpanContext from the
  25. // SpanContext method.
  26. func ContextWithSpanContext(parent context.Context, sc SpanContext) context.Context {
  27. return ContextWithSpan(parent, nonRecordingSpan{sc: sc})
  28. }
  29. // ContextWithRemoteSpanContext returns a copy of parent with rsc set explicly
  30. // as a remote SpanContext and as the current Span. The Span implementation
  31. // that wraps rsc is non-recording and performs no operations other than to
  32. // return rsc as the SpanContext from the SpanContext method.
  33. func ContextWithRemoteSpanContext(parent context.Context, rsc SpanContext) context.Context {
  34. return ContextWithSpanContext(parent, rsc.WithRemote(true))
  35. }
  36. // SpanFromContext returns the current Span from ctx.
  37. //
  38. // If no Span is currently set in ctx an implementation of a Span that
  39. // performs no operations is returned.
  40. func SpanFromContext(ctx context.Context) Span {
  41. if ctx == nil {
  42. return noopSpan{}
  43. }
  44. if span, ok := ctx.Value(currentSpanKey).(Span); ok {
  45. return span
  46. }
  47. return noopSpan{}
  48. }
  49. // SpanContextFromContext returns the current Span's SpanContext.
  50. func SpanContextFromContext(ctx context.Context) SpanContext {
  51. return SpanFromContext(ctx).SpanContext()
  52. }