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
SpanContextassociated with thisSpan.The
SpanContextcontains state that propagates fromSpantoSpanin a larger trace.- Return type
- Returns
the
SpanContextassociated with thisSpan.
-
finish(finish_time=None)¶ Indicates that the work represented by this
Spanhas completed or terminated.With the exception of the
Span.contextproperty, the semantics of all otherSpanmethods are undefined afterSpan.finish()has been invoked.
-
get_baggage_item(key)¶ Retrieves value of the baggage item with the given key.
-
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)
-
set_baggage_item(key, value)¶ Stores a Baggage item in the
Spanas 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.
-
set_operation_name(operation_name)¶ Changes the operation name.
-
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
Traceris undefined, i.e. it is implementation specific whether theTracerwill retain the first value, or the last value, or pick one randomly, or even keep all of them.
-
property
-
class
opentracing.SpanContext¶ SpanContext represents
Spanstate that must propagate to descendantSpans and across process boundaries.SpanContext is logically divided into two pieces: the user-level “Baggage” (see
Span.set_baggage_item()andSpan.get_baggage_item()) that propagates acrossSpanboundaries and any tracer-implementation-specific fields that are needed to identify or otherwise contextualize the associatedSpan(e.g., a(trace_id, span_id, sampled)tuple).-
property
baggage¶ Return baggage associated with this
SpanContext. If no baggage has been added to theSpan, returns an empty dict.The caller must not modify the returned dictionary.
See also:
Span.set_baggage_item()/Span.get_baggage_item()- Return type
- Returns
baggage associated with this
SpanContextor{}.
-
property
-
class
opentracing.Scope(manager, span)¶ A scope formalizes the activation and deactivation of a
Span, usually from a CPU standpoint. Many times aSpanwill be extant (in thatSpan.finish()has not been called) despite being in a non-runnable state from a CPU/scheduler standpoint. For instance, aSpanrepresenting the client side of an RPC will be unfinished but blocked on IO while the RPC is still outstanding. A scope defines when a givenSpanis scheduled and on the path.- Parameters
manager (ScopeManager) – the
ScopeManagerthat created thisScope.
-
close()¶ Marks the end of the active period for this
Scope, updatingScopeManager.activein the process.NOTE: Calling this method more than once on a single
Scopeleads to undefined behavior.
-
property
manager¶ Returns the
ScopeManagerthat created thisScope.- Return type
-
class
opentracing.ScopeManager¶ The
ScopeManagerinterface abstracts both the activation of aSpanand access to an activeSpan/Scope.-
activate(span, finish_on_close)¶ Makes a
Spanactive.- Parameters
span – the
Spanthat should become active.finish_on_close – whether
Spanshould be automatically finished whenScope.close()is called.
- Return type
- Returns
a
Scopeto control the end of the active period for span. It is a programming error to neglect to callScope.close()on the returned instance.
-
property
active¶ Returns the currently active
Scopewhich can be used to access the currently activeScope.span.If there is a non-null
Scope, its wrappedSpanbecomes an implicit parent of any newly-createdSpanatTracer.start_active_span()time.
-
-
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 forTracer.scope_manager.active.span, andNonewill be returned ifScope.spanisNone.
-
extract(format, carrier)¶ Returns a
SpanContextinstance extracted from a carrier of the given format, orNoneif no suchSpanContextcould be found.The type of carrier is determined by format. See the
Formatclass/namespace for the built-in OpenTracing formats.Implementations must raise
UnsupportedFormatExceptionif 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
- Returns
a
SpanContextextracted from carrier orNoneif no suchSpanContextcould be found.
-
inject(span_context, format, carrier)¶ Injects span_context into carrier.
The type of carrier is determined by format. See the
Formatclass/namespace for the built-in OpenTracing formats.Implementations must raise
UnsupportedFormatExceptionif format is unknown or disallowed.- Parameters
span_context (SpanContext) – the
SpanContextinstance to injectformat (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
-
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
Scopesupports 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
Spanwhen theScopecontext 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
Spanfrom the perspective of the current service.child_of (Span or SpanContext) – (optional) a
SpanorSpanContextinstance representing the parent in a REFERENCE_CHILD_OF reference. If specified, the references parameter must be omitted.references (
listofReference) – (optional) references that identify one or more parentSpanContexts. (See the Reference documentation for detail).tags (dict) – an optional dictionary of
Spantags. The caller gives up ownership of that dictionary, because theTracermay use it as-is to avoid extra data copying.start_time (float) – an explicit
Spanstart time as a unix timestamp pertime.time().ignore_active_span (bool) – (optional) an explicit flag that ignores the current active
Scopeand creates a rootSpan.finish_on_close (bool) – whether
Spanshould automatically be finished whenScope.close()is called.
- Return type
- Returns
a
Scope, already registered via theScopeManager.
-
start_span(operation_name=None, child_of=None, references=None, tags=None, start_time=None, ignore_active_span=False)¶ Starts and returns a new
Spanrepresenting a unit of work.Starting a root
Span(aSpanwith no causal references):tracer.start_span('...')
Starting a child
Span(see alsostart_child_span()):tracer.start_span( '...', child_of=parent_span)
Starting a child
Spanin 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
Spanfrom the perspective of the current service.child_of (Span or SpanContext) – (optional) a
SpanorSpanContextrepresenting the parent in a REFERENCE_CHILD_OF reference. If specified, the references parameter must be omitted.references (
listofReference) – (optional) references that identify one or more parentSpanContexts. (See the Reference documentation for detail).tags (dict) – an optional dictionary of
Spantags. The caller gives up ownership of that dictionary, because theTracermay 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
Scopeand creates a rootSpan.
- Return type
- Returns
an already-started
Spaninstance.
-
property
-
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 betweenSpans.Tracerimplementations must ignore references where referenced_context isNone. This behavior allows for simpler code when an inbound RPC request contains no tracing information and as a resultTracer.extract()returnsNone:parent_ref = tracer.extract(opentracing.HTTP_HEADERS, request.headers) span = tracer.start_span( 'operation', references=child_of(parent_ref) )
See
child_of()andfollows_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()andTracer.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()andTracer.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
SpanContexts in a pythondictmapping 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
dictmay contain unrelated data (e.g., arbitrary gRPC metadata). As such, theTracerimplementation should use a prefix or other convention to distinguish tracer-specific key:value pairs.
-
TEXT_MAP= 'text_map'¶ The TEXT_MAP format represents
SpanContexts in a pythondictmapping from strings to strings.Both the keys and the values have unrestricted character sets (unlike the HTTP_HEADERS format).
NOTE: The TEXT_MAP carrier
dictmay contain unrelated data (e.g., arbitrary gRPC metadata). As such, theTracerimplementation 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
- Returns
The global tracer instance.
-
opentracing.set_global_tracer(value)¶ Sets the global tracer. It is an error to pass
None.
-
opentracing.start_child_span(parent_span, operation_name, tags=None, start_time=None)¶ A shorthand method that starts a child_of
Spanfor a given parentSpan.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
Spanwhich will act as the parent in the returnedSpans child_of reference.operation_name (str) – the operation name for the child
Spaninstancetags (dict) – optional dict of
Spantags. The caller gives up ownership of that dict, because theTracermay use it as-is to avoid extra data copying.start_time (float) – an explicit
Spanstart time as a unix timestamp pertime.time().
- Return type
- Returns
an already-started
Spaninstance.
-
opentracing.child_of(referenced_context=None)¶ child_of is a helper that creates CHILD_OF References.
- Parameters
referenced_context (SpanContext) – the (causal parent)
SpanContextto reference. IfNoneis passed, this reference must be ignored by theTracer.- Return type
- 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)
SpanContextto reference. IfNoneis passed, this reference must be ignored by theTracer.- Return type
- 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()andTracer.extract().
-
class
opentracing.SpanContextCorruptedException¶ SpanContextCorruptedException should be used when the underlying
SpanContextstate is seemingly present but not well-formed.See
Tracer.inject()andTracer.extract().
-
class
opentracing.UnsupportedFormatException¶ UnsupportedFormatException should be used when the provided format value is unknown or disallowed by the
Tracer.See
Tracer.inject()andTracer.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
Tracerimplementation for tests, a developer can assert thatSpanproperties and relationships with other Spans are defined as expected by instrumentation code.By default, MockTracer registers propagators for
Format.TEXT_MAP,Format.HTTP_HEADERSandFormat.BINARY. The user should callregister_propagator()for each additional inject/extract format.-
extract(format, carrier)¶ Returns a
SpanContextinstance extracted from a carrier of the given format, orNoneif no suchSpanContextcould be found.The type of carrier is determined by format. See the
Formatclass/namespace for the built-in OpenTracing formats.Implementations must raise
UnsupportedFormatExceptionif 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
- Returns
a
SpanContextextracted from carrier orNoneif no suchSpanContextcould 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
- 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
Formatclass/namespace for the built-in OpenTracing formats.Implementations must raise
UnsupportedFormatExceptionif format is unknown or disallowed.- Parameters
span_context (SpanContext) – the
SpanContextinstance to injectformat (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.
-
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 theyfinish().
-
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
Scopesupports 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
Spanwhen theScopecontext 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
Spanfrom the perspective of the current service.child_of (Span or SpanContext) – (optional) a
SpanorSpanContextinstance representing the parent in a REFERENCE_CHILD_OF reference. If specified, the references parameter must be omitted.references (
listofReference) – (optional) references that identify one or more parentSpanContexts. (See the Reference documentation for detail).tags (dict) – an optional dictionary of
Spantags. The caller gives up ownership of that dictionary, because theTracermay use it as-is to avoid extra data copying.start_time (float) – an explicit
Spanstart time as a unix timestamp pertime.time().ignore_active_span (bool) – (optional) an explicit flag that ignores the current active
Scopeand creates a rootSpan.finish_on_close (bool) – whether
Spanshould automatically be finished whenScope.close()is called.
- Return type
- Returns
a
Scope, already registered via theScopeManager.
-
start_span(operation_name=None, child_of=None, references=None, tags=None, start_time=None, ignore_active_span=False)¶ Starts and returns a new
Spanrepresenting a unit of work.Starting a root
Span(aSpanwith no causal references):tracer.start_span('...')
Starting a child
Span(see alsostart_child_span()):tracer.start_span( '...', child_of=parent_span)
Starting a child
Spanin 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
Spanfrom the perspective of the current service.child_of (Span or SpanContext) – (optional) a
SpanorSpanContextrepresenting the parent in a REFERENCE_CHILD_OF reference. If specified, the references parameter must be omitted.references (
listofReference) – (optional) references that identify one or more parentSpanContexts. (See the Reference documentation for detail).tags (dict) – an optional dictionary of
Spantags. The caller gives up ownership of that dictionary, because theTracermay 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
Scopeand creates a rootSpan.
- Return type
- Returns
an already-started
Spaninstance.
-
Scope managers¶
-
class
opentracing.scope_managers.ThreadLocalScopeManager¶ ScopeManagerimplementation that stores the current activeScopeusing thread-local storage.-
activate(span, finish_on_close)¶ Make a
Spaninstance active.- Parameters
span – the
Spanthat should become active.finish_on_close – whether span should automatically be finished when
Scope.close()is called.
- Returns
a
Scopeinstance to control the end of the active period for theSpan. It is a programming error to neglect to callScope.close()on the returned instance.
-
-
class
opentracing.scope_managers.gevent.GeventScopeManager¶ ScopeManagerimplementation for gevent that stores theScopein the current greenlet (gevent.getcurrent()).Automatic
Spanpropagation 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
Spaninstance active.- Parameters
span – the
Spanthat should become active.finish_on_close – whether span should automatically be finished when
Scope.close()is called.
- Returns
a
Scopeinstance to control the end of the active period for theSpan. It is a programming error to neglect to callScope.close()on the returned instance.
-
-
class
opentracing.scope_managers.asyncio.AsyncioScopeManager¶ ScopeManagerimplementation for asyncio that stores theScopein the currentTask(asyncio.current_task()), falling back to thread-local storage if none was being executed.Automatic
Spanpropagation 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) ...