__init__.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. # Copyright The OpenTelemetry Authors
  2. # SPDX-License-Identifier: Apache-2.0
  3. from opentelemetry.context import create_key, get_value, set_value
  4. from opentelemetry.context.context import Context
  5. from opentelemetry.trace.span import INVALID_SPAN, Span
  6. SPAN_KEY = "current-span"
  7. _SPAN_KEY = create_key("current-span")
  8. def set_span_in_context(span: Span, context: Context | None = None) -> Context:
  9. """Set the span in the given context.
  10. Args:
  11. span: The Span to set.
  12. context: a Context object. if one is not passed, the
  13. default current context is used instead.
  14. """
  15. ctx = set_value(_SPAN_KEY, span, context=context)
  16. return ctx
  17. def get_current_span(context: Context | None = None) -> Span:
  18. """Retrieve the current span.
  19. Args:
  20. context: A Context object. If one is not passed, the
  21. default current context is used instead.
  22. Returns:
  23. The Span set in the context if it exists. INVALID_SPAN otherwise.
  24. """
  25. span = get_value(_SPAN_KEY, context=context)
  26. if span is None or not isinstance(span, Span):
  27. return INVALID_SPAN
  28. return span