# Python API

## Classes

class `opentracing.``Span`(tracer, context)

  Span represents a unit of work executed on behalf of a trace. Examples of spans include a remote procedure call, or a in-process method call to a sub-component. Every span in a trace may have zero or more causal parents, and these relationships transitively form a DAG. It is common for spans to have at most one parent, and thus most traces are merely tree structures.

  Span implements a context manager API that allows the following usage:

      with tracer.start_span(operation_name='go_fishing') as span:
          call_some_service()

  In the context manager syntax it’s not necessary to call `Span.finish()`

  property `context`

    Provides access to the `SpanContext` associated with this `Span`.

    The `SpanContext` contains state that propagates from `Span` to `Span` in a larger trace.

    Return type

      SpanContext

    Returns

      the `SpanContext` associated with this `Span`.

  `finish`(finish_time=None)

    Indicates that the work represented by this `Span` has completed or terminated.

    With the exception of the `Span.context` property, the semantics of all other `Span` methods are undefined after `Span.finish()` has been invoked.

    Parameters

      finish_time (float) – an explicit `Span` finish timestamp as a unix timestamp per `time.time()`

  `get_baggage_item`(key)

    Retrieves value of the baggage item with the given key.

    Parameters

      key (str) – key of the baggage item

    Return type

      str

    Returns

      value of the baggage item with given key, or `None`.

  `log`(**kwargs)

    DEPRECATED

  `log_event`(event, payload=None)

    DEPRECATED

  `log_kv`(key_values, timestamp=None)

    Adds a log record to the `Span`.

    For example:

        span.log_kv({
            "event": "time to first byte",
            "packet.size": packet.size()})

        span.log_kv({"event": "two minutes ago"}, time.time() - 120)

    Parameters

      - key_values (dict) – A dict of string keys and values of any type

      - timestamp (float) – A unix timestamp per `time.time()`; current time if `None`

    Return type

      Span

    Returns

      the `Span` itself, for call chaining.

  `set_baggage_item`(key, value)

    Stores a Baggage item in the `Span` as a key/value pair.

    Enables powerful distributed context propagation functionality where arbitrary application data can be carried along the full path of request execution throughout the system.

    Note 1: Baggage is only propagated to the future (recursive) children of this `Span`.

    Note 2: Baggage is sent in-band with every subsequent local and remote calls, so this feature must be used with care.

    Parameters

      - key (str) – Baggage item key

      - value (str) – Baggage item value

    Return type

      Span

    Returns

      itself, for chaining the calls.

  `set_operation_name`(operation_name)

    Changes the operation name.

    Parameters

      operation_name (str) – the new operation name

    Return type

      Span

    Returns

      the `Span` itself, for call chaining.

  `set_tag`(key, value)

    Attaches a key/value pair to the `Span`.

    The value must be a string, a bool, or a numeric type.

    If the user calls set_tag multiple times for the same key, the behavior of the `Tracer` is undefined, i.e. it is implementation specific whether the `Tracer` will retain the first value, or the last value, or pick one randomly, or even keep all of them.

    Parameters

      - key (str) – key or name of the tag. Must be a string.

      - value (string or bool or int or float) – value of the tag.

    Return type

      Span

    Returns

      the `Span` itself, for call chaining.

  property `tracer`

    Provides access to the `Tracer` that created this `Span`.

    Return type

      Tracer

    Returns

      the `Tracer` that created this `Span`.

class `opentracing.``SpanContext`

  SpanContext represents `Span` state that must propagate to descendant `Span`s and across process boundaries.

  SpanContext is logically divided into two pieces: the user-level “Baggage” (see `Span.set_baggage_item()` and `Span.get_baggage_item()`) that propagates across `Span` boundaries and any tracer-implementation-specific fields that are needed to identify or otherwise contextualize the associated `Span` (e.g., a `(trace_id, span_id, sampled)` tuple).

  property `baggage`

    Return baggage associated with this `SpanContext`. If no baggage has been added to the `Span`, returns an empty dict.

    The caller must not modify the returned dictionary.

    See also: `Span.set_baggage_item()` / `Span.get_baggage_item()`

    Return type

      dict

    Returns

      baggage associated with this `SpanContext` or `{}`.

class `opentracing.``Scope`(manager, span)

  A scope formalizes the activation and deactivation of a `Span`, usually from a CPU standpoint. Many times a `Span` will be extant (in that `Span.finish()` has not been called) despite being in a non-runnable state from a CPU/scheduler standpoint. For instance, a `Span` representing the client side of an RPC will be unfinished but blocked on IO while the RPC is still outstanding. A scope defines when a given `Span` is scheduled and on the path.

  Parameters

    - manager (ScopeManager) – the `ScopeManager` that created this `Scope`.

    - span (Span) – the `Span` used for this `Scope`.

  `close`()

    Marks the end of the active period for this `Scope`, updating `ScopeManager.active` in the process.

    NOTE: Calling this method more than once on a single `Scope` leads to undefined behavior.

  property `manager`

    Returns the `ScopeManager` that created this `Scope`.

    Return type

      ScopeManager

  property `span`

    Returns the `Span` wrapped by this `Scope`.

    Return type

      Span

class `opentracing.``ScopeManager`

  The `ScopeManager` interface abstracts both the activation of a `Span` and access to an active `Span`/`Scope`.

  `activate`(span, finish_on_close)

    Makes a `Span` active.

    Parameters

      - span – the `Span` that should become active.

      - finish_on_close – whether `Span` should be automatically finished when `Scope.close()` is called.

    Return type

      Scope

    Returns

      a `Scope` to control the end of the active period for span. It is a programming error to neglect to call `Scope.close()` on the returned instance.

  property `active`

    Returns the currently active `Scope` which can be used to access the currently active `Scope.span`.

    If there is a non-null `Scope`, its wrapped `Span` becomes an implicit parent of any newly-created `Span` at `Tracer.start_active_span()` time.

    Return type

      Scope

    Returns

      the `Scope` that is active, or `None` if not available.

class `opentracing.``Tracer`(scope_manager=None)

  Tracer is the entry point API between instrumentation code and the tracing implementation.

  This implementation both defines the public Tracer API, and provides a default no-op behavior.

  property `active_span`

    Provides access to the the active `Span`. This is a shorthand for `Tracer.scope_manager.active.span`, and `None` will be returned if `Scope.span` is `None`.

    Return type

      `Span`

    Returns

      the active `Span`.

  `extract`(format, carrier)

    Returns a `SpanContext` instance extracted from a carrier of the given format, or `None` if no such `SpanContext` could be found.

    The type of carrier is determined by format. See the `Format` class/namespace for the built-in OpenTracing formats.

    Implementations must raise `UnsupportedFormatException` if format is unknown or disallowed.

    Implementations may raise `InvalidCarrierException`, `SpanContextCorruptedException`, or implementation-specific errors if there are problems with carrier.

    Parameters

      - format – a python object instance that represents a given carrier format. format may be of any type, and format equality is defined by python `==` equality.

      - carrier – the format-specific carrier object to extract from

    Return type

      SpanContext

    Returns

      a `SpanContext` extracted from carrier or `None` if no such `SpanContext` could be found.

  `inject`(span_context, format, carrier)

    Injects span_context into carrier.

    The type of carrier is determined by format. See the `Format` class/namespace for the built-in OpenTracing formats.

    Implementations must raise `UnsupportedFormatException` if format is unknown or disallowed.

    Parameters

      - span_context (SpanContext) – the `SpanContext` instance to inject

      - format (Format) – a python object instance that represents a given carrier format. format may be of any type, and format equality is defined by python `==` equality.

      - carrier – the format-specific carrier object to inject into

  property `scope_manager`

    Provides access to the current `ScopeManager`.

    Return type

      `ScopeManager`

  `start_active_span`(operation_name, child_of=None, references=None, tags=None, start_time=None, ignore_active_span=False, finish_on_close=True)

    Returns a newly started and activated `Scope`.

    The returned `Scope` supports with-statement contexts. For example:

        with tracer.start_active_span('...') as scope:
            scope.span.set_tag('http.method', 'GET')
            do_some_work()
        # Span.finish() is called as part of scope deactivation through
        # the with statement.

    It’s also possible to not finish the `Span` when the `Scope` context expires:

        with tracer.start_active_span('...',
                                      finish_on_close=False) as scope:
            scope.span.set_tag('http.method', 'GET')
            do_some_work()
        # Span.finish() is not called as part of Scope deactivation as
        # `finish_on_close` is `False`.

    Parameters

      - operation_name (str) – name of the operation represented by the new `Span` from the perspective of the current service.

      - child_of (Span or SpanContext) – (optional) a `Span` or `SpanContext` instance representing the parent in a REFERENCE_CHILD_OF reference. If specified, the references parameter must be omitted.

      - references (`list` of `Reference`) – (optional) references that identify one or more parent `SpanContext`s. (See the Reference documentation for detail).

      - tags (dict) – an optional dictionary of `Span` tags. The caller gives up ownership of that dictionary, because the `Tracer` may use it as-is to avoid extra data copying.

      - start_time (float) – an explicit `Span` start time as a unix timestamp per `time.time()`.

      - ignore_active_span (bool) – (optional) an explicit flag that ignores the current active `Scope` and creates a root `Span`.

      - finish_on_close (bool) – whether `Span` should automatically be finished when `Scope.close()` is called.

    Return type

      Scope

    Returns

      a `Scope`, already registered via the `ScopeManager`.

  `start_span`(operation_name=None, child_of=None, references=None, tags=None, start_time=None, ignore_active_span=False)

    Starts and returns a new `Span` representing a unit of work.

    Starting a root `Span` (a `Span` with no causal references):

        tracer.start_span('...')

    Starting a child `Span` (see also `start_child_span()`):

        tracer.start_span(
            '...',
            child_of=parent_span)

    Starting a child `Span` in a more verbose way:

        tracer.start_span(
            '...',
            references=[opentracing.child_of(parent_span)])

    Parameters

      - operation_name (str) – name of the operation represented by the new `Span` from the perspective of the current service.

      - child_of (Span or SpanContext) – (optional) a `Span` or `SpanContext` representing the parent in a REFERENCE_CHILD_OF reference. If specified, the references parameter must be omitted.

      - references (`list` of `Reference`) – (optional) references that identify one or more parent `SpanContext`s. (See the Reference documentation for detail).

      - tags (dict) – an optional dictionary of `Span` tags. The caller gives up ownership of that dictionary, because the `Tracer` may use it as-is to avoid extra data copying.

      - start_time (float) – an explicit Span start time as a unix timestamp per `time.time()`

      - ignore_active_span (bool) – an explicit flag that ignores the current active `Scope` and creates a root `Span`.

    Return type

      Span

    Returns

      an already-started `Span` instance.

class `opentracing.``ReferenceType`

  A namespace for OpenTracing reference types.

  See http://opentracing.io/spec for more detail about references, reference types, and CHILD_OF and FOLLOWS_FROM in particular.

class `opentracing.``Reference`(type, referenced_context)

  A Reference pairs a reference type with a referenced `SpanContext`.

  References are used by `Tracer.start_span()` to describe the relationships between `Span`s.

  `Tracer` implementations must ignore references where referenced_context is `None`. This behavior allows for simpler code when an inbound RPC request contains no tracing information and as a result `Tracer.extract()` returns `None`:

      parent_ref = tracer.extract(opentracing.HTTP_HEADERS, request.headers)
      span = tracer.start_span(
          'operation', references=child_of(parent_ref)
      )

  See `child_of()` and `follows_from()` helpers for creating these references.

class `opentracing.``Format`

  A namespace for builtin carrier formats.

  These static constants are intended for use in the `Tracer.inject()` and `Tracer.extract()` methods. E.g.:

      tracer.inject(span.context, Format.BINARY, binary_carrier)

  `BINARY` = 'binary'

    The BINARY format represents SpanContexts in an opaque bytearray carrier.

    For both `Tracer.inject()` and `Tracer.extract()` the carrier should be a bytearray instance. `Tracer.inject()` must append to the bytearray carrier (rather than replace its contents).

  `HTTP_HEADERS` = 'http_headers'

    The HTTP_HEADERS format represents `SpanContext`s in a python `dict` mapping from character-restricted strings to strings.

    Keys and values in the HTTP_HEADERS carrier must be suitable for use as HTTP headers (without modification or further escaping). That is, the keys have a greatly restricted character set, casing for the keys may not be preserved by various intermediaries, and the values should be URL-escaped.

    NOTE: The HTTP_HEADERS carrier `dict` may contain unrelated data (e.g., arbitrary gRPC metadata). As such, the `Tracer` implementation should use a prefix or other convention to distinguish tracer-specific key:value pairs.

  `TEXT_MAP` = 'text_map'

    The TEXT_MAP format represents `SpanContext`s in a python `dict` mapping from strings to strings.

    Both the keys and the values have unrestricted character sets (unlike the HTTP_HEADERS format).

    NOTE: The TEXT_MAP carrier `dict` may contain unrelated data (e.g., arbitrary gRPC metadata). As such, the `Tracer` implementation should use a prefix or other convention to distinguish tracer-specific key:value pairs.

## Utility Functions

`opentracing.``global_tracer`()

  Returns the global tracer. The default value is an instance of `opentracing.Tracer`

  Return type

    `Tracer`

  Returns

    The global tracer instance.

`opentracing.``set_global_tracer`(value)

  Sets the global tracer. It is an error to pass `None`.

  Parameters

    value (`Tracer`) – the `Tracer` used as global instance.

`opentracing.``start_child_span`(parent_span, operation_name, tags=None, start_time=None)

  A shorthand method that starts a child_of `Span` for a given parent `Span`.

  Equivalent to calling:

      parent_span.tracer().start_span(
          operation_name,
          references=opentracing.child_of(parent_span.context),
          tags=tags,
          start_time=start_time)

  Parameters

    - parent_span (Span) – the `Span` which will act as the parent in the returned `Span`s child_of reference.

    - operation_name (str) – the operation name for the child `Span` instance

    - tags (dict) – optional dict of `Span` tags. The caller gives up ownership of that dict, because the `Tracer` may use it as-is to avoid extra data copying.

    - start_time (float) – an explicit `Span` start time as a unix timestamp per `time.time()`.

  Return type

    Span

  Returns

    an already-started `Span` instance.

`opentracing.``child_of`(referenced_context=None)

  child_of is a helper that creates CHILD_OF References.

  Parameters

    referenced_context (SpanContext) – the (causal parent) `SpanContext` to reference. If `None` is passed, this reference must be ignored by the `Tracer`.

  Return type

    Reference

  Returns

    A reference suitable for `Tracer.start_span(..., references=...)`

`opentracing.``follows_from`(referenced_context=None)

  follows_from is a helper that creates FOLLOWS_FROM References.

  Parameters

    referenced_context (SpanContext) – the (causal parent) `SpanContext` to reference. If `None` is passed, this reference must be ignored by the `Tracer`.

  Return type

    Reference

  Returns

    A Reference suitable for `Tracer.start_span(..., references=...)`

## Exceptions

class `opentracing.``InvalidCarrierException`

  InvalidCarrierException should be used when the provided carrier instance does not match what the format argument requires.

  See `Tracer.inject()` and `Tracer.extract()`.

class `opentracing.``SpanContextCorruptedException`

  SpanContextCorruptedException should be used when the underlying `SpanContext` state is seemingly present but not well-formed.

  See `Tracer.inject()` and `Tracer.extract()`.

class `opentracing.``UnsupportedFormatException`

  UnsupportedFormatException should be used when the provided format value is unknown or disallowed by the `Tracer`.

  See `Tracer.inject()` and `Tracer.extract()`.

## MockTracer

class `opentracing.mocktracer.``MockTracer`(scope_manager=None)

  MockTracer makes it easy to test the semantics of OpenTracing instrumentation.

  By using a MockTracer as a `Tracer` implementation for tests, a developer can assert that `Span` properties and relationships with other Spans are defined as expected by instrumentation code.

  By default, MockTracer registers propagators for `Format.TEXT_MAP`, `Format.HTTP_HEADERS` and `Format.BINARY`. The user should call `register_propagator()` for each additional inject/extract format.

  `extract`(format, carrier)

    Returns a `SpanContext` instance extracted from a carrier of the given format, or `None` if no such `SpanContext` could be found.

    The type of carrier is determined by format. See the `Format` class/namespace for the built-in OpenTracing formats.

    Implementations must raise `UnsupportedFormatException` if format is unknown or disallowed.

    Implementations may raise `InvalidCarrierException`, `SpanContextCorruptedException`, or implementation-specific errors if there are problems with carrier.

    Parameters

      - format – a python object instance that represents a given carrier format. format may be of any type, and format equality is defined by python `==` equality.

      - carrier – the format-specific carrier object to extract from

    Return type

      SpanContext

    Returns

      a `SpanContext` extracted from carrier or `None` if no such `SpanContext` could be found.

  `finished_spans`()

    Return a copy of all finished Spans started by this MockTracer (since construction or the last call to `reset()`)

    Return type

      list

    Returns

      a copy of the finished Spans.

  `inject`(span_context, format, carrier)

    Injects span_context into carrier.

    The type of carrier is determined by format. See the `Format` class/namespace for the built-in OpenTracing formats.

    Implementations must raise `UnsupportedFormatException` if format is unknown or disallowed.

    Parameters

      - span_context (SpanContext) – the `SpanContext` instance to inject

      - format (Format) – a python object instance that represents a given carrier format. format may be of any type, and format equality is defined by python `==` equality.

      - carrier – the format-specific carrier object to inject into

  `register_propagator`(format, propagator)

    Register a propagator with this MockTracer.

    Parameters

      - format (string) – a `Format` identifier like `TEXT_MAP`

      - propagator (Propagator) – a Propagator instance to handle inject/extract calls involving format

  `reset`()

    Clear the finished Spans queue.

    Note that this does not have any effect on Spans created by MockTracer that have not finished yet; those will still be enqueued in `finished_spans()` when they `finish()`.

  `start_active_span`(operation_name, child_of=None, references=None, tags=None, start_time=None, ignore_active_span=False, finish_on_close=True)

    Returns a newly started and activated `Scope`.

    The returned `Scope` supports with-statement contexts. For example:

        with tracer.start_active_span('...') as scope:
            scope.span.set_tag('http.method', 'GET')
            do_some_work()
        # Span.finish() is called as part of scope deactivation through
        # the with statement.

    It’s also possible to not finish the `Span` when the `Scope` context expires:

        with tracer.start_active_span('...',
                                      finish_on_close=False) as scope:
            scope.span.set_tag('http.method', 'GET')
            do_some_work()
        # Span.finish() is not called as part of Scope deactivation as
        # `finish_on_close` is `False`.

    Parameters

      - operation_name (str) – name of the operation represented by the new `Span` from the perspective of the current service.

      - child_of (Span or SpanContext) – (optional) a `Span` or `SpanContext` instance representing the parent in a REFERENCE_CHILD_OF reference. If specified, the references parameter must be omitted.

      - references (`list` of `Reference`) – (optional) references that identify one or more parent `SpanContext`s. (See the Reference documentation for detail).

      - tags (dict) – an optional dictionary of `Span` tags. The caller gives up ownership of that dictionary, because the `Tracer` may use it as-is to avoid extra data copying.

      - start_time (float) – an explicit `Span` start time as a unix timestamp per `time.time()`.

      - ignore_active_span (bool) – (optional) an explicit flag that ignores the current active `Scope` and creates a root `Span`.

      - finish_on_close (bool) – whether `Span` should automatically be finished when `Scope.close()` is called.

    Return type

      Scope

    Returns

      a `Scope`, already registered via the `ScopeManager`.

  `start_span`(operation_name=None, child_of=None, references=None, tags=None, start_time=None, ignore_active_span=False)

    Starts and returns a new `Span` representing a unit of work.

    Starting a root `Span` (a `Span` with no causal references):

        tracer.start_span('...')

    Starting a child `Span` (see also `start_child_span()`):

        tracer.start_span(
            '...',
            child_of=parent_span)

    Starting a child `Span` in a more verbose way:

        tracer.start_span(
            '...',
            references=[opentracing.child_of(parent_span)])

    Parameters

      - operation_name (str) – name of the operation represented by the new `Span` from the perspective of the current service.

      - child_of (Span or SpanContext) – (optional) a `Span` or `SpanContext` representing the parent in a REFERENCE_CHILD_OF reference. If specified, the references parameter must be omitted.

      - references (`list` of `Reference`) – (optional) references that identify one or more parent `SpanContext`s. (See the Reference documentation for detail).

      - tags (dict) – an optional dictionary of `Span` tags. The caller gives up ownership of that dictionary, because the `Tracer` may use it as-is to avoid extra data copying.

      - start_time (float) – an explicit Span start time as a unix timestamp per `time.time()`

      - ignore_active_span (bool) – an explicit flag that ignores the current active `Scope` and creates a root `Span`.

    Return type

      Span

    Returns

      an already-started `Span` instance.

## Scope managers

class `opentracing.scope_managers.``ThreadLocalScopeManager`

  `ScopeManager` implementation that stores the current active `Scope` using thread-local storage.

  `activate`(span, finish_on_close)

    Make a `Span` instance active.

    Parameters

      - span – the `Span` that should become active.

      - finish_on_close – whether span should automatically be finished when `Scope.close()` is called.

    Returns

      a `Scope` instance to control the end of the active period for the `Span`. It is a programming error to neglect to call `Scope.close()` on the returned instance.

  property `active`

    Return the currently active `Scope` which can be used to access the currently active `Scope.span`.

    Returns

      the `Scope` that is active, or `None` if not available.

class `opentracing.scope_managers.gevent.``GeventScopeManager`

  `ScopeManager` implementation for gevent that stores the `Scope` in the current greenlet (`gevent.getcurrent()`).

  Automatic `Span` propagation from parent greenlets to their children is not provided, which needs to be done manually:

      def child_greenlet(span):
          # activate the parent Span, but do not finish it upon
          # deactivation. That will be done by the parent greenlet.
          with tracer.scope_manager.activate(span, finish_on_close=False):
              with tracer.start_active_span('child') as scope:
                  ...

      def parent_greenlet():
          with tracer.start_active_span('parent') as scope:
              ...
              gevent.spawn(child_greenlet, span).join()
              ...

  `activate`(span, finish_on_close)

    Make a `Span` instance active.

    Parameters

      - span – the `Span` that should become active.

      - finish_on_close – whether span should automatically be finished when `Scope.close()` is called.

    Returns

      a `Scope` instance to control the end of the active period for the `Span`. It is a programming error to neglect to call `Scope.close()` on the returned instance.

  property `active`

    Return the currently active `Scope` which can be used to access the currently active `Scope.span`.

    Returns

      the `Scope` that is active, or `None` if not available.

class `opentracing.scope_managers.asyncio.``AsyncioScopeManager`

  `ScopeManager` implementation for asyncio that stores the `Scope` in the current `Task` (`asyncio.current_task()`), falling back to thread-local storage if none was being executed.

  Automatic `Span` propagation from parent coroutines to their children is not provided, which needs to be done manually:

      async def child_coroutine(span):
          # activate the parent Span, but do not finish it upon
          # deactivation. That will be done by the parent coroutine.
          with tracer.scope_manager.activate(span, finish_on_close=False):
              with tracer.start_active_span('child') as scope:
                  ...

      async def parent_coroutine():
          with tracer.start_active_span('parent') as scope:
              ...
              await child_coroutine(span)
              ...

  `activate`(span, finish_on_close)

    Make a `Span` instance active.

    Parameters

      - span – the `Span` that should become active.

      - finish_on_close – whether span should automatically be finished when `Scope.close()` is called.

    If no `Task` is being executed, thread-local storage will be used to store the `Scope`.

    Returns

      a `Scope` instance to control the end of the active period for the `Span`. It is a programming error to neglect to call `Scope.close()` on the returned instance.

  property `active`

    Return the currently active `Scope` which can be used to access the currently active `Scope.span`.

    Returns

      the `Scope` that is active, or `None` if not available.