opentelemetry.trace package¶
Module contents¶
The OpenTelemetry tracing API describes the classes used to generate distributed traces.
The Tracer
class controls access to the execution context, and
manages span creation. Each operation in a trace is represented by a
Span
, which records the start, end time, and metadata associated with
the operation.
This module provides abstract (i.e. unimplemented) classes required for
tracing, and a concrete no-op DefaultSpan
that allows applications
to use the API package alone without a supporting implementation.
To get a tracer, you need to provide the package name from which you are
calling the tracer APIs to OpenTelemetry by calling TracerProvider.get_tracer
with the calling module name and the version of your package.
The tracer supports creating spans that are “attached” or “detached” from the context. New spans are “attached” to the context in that they are created as children of the currently active span, and the newly-created span can optionally become the new active span:
from opentelemetry import trace
tracer = trace.get_tracer(__name__)
# Create a new root span, set it as the current span in context
with tracer.start_as_current_span("parent"):
# Attach a new child and update the current span
with tracer.start_as_current_span("child"):
do_work():
# Close child span, set parent as current
# Close parent span, set default span as current
When creating a span that’s “detached” from the context the active span doesn’t change, and the caller is responsible for managing the span’s lifetime:
# Explicit parent span assignment
child = tracer.start_span("child", parent=parent)
try:
do_work(span=child)
finally:
child.end()
Applications should generally use a single global TracerProvider, and use either implicit or explicit context propagation consistently throughout.
New in version 0.1.0.
Changed in version 0.3.0: TracerProvider
was introduced and the global tracer
getter was
replaced by tracer_provider
.
Changed in version 0.5.0: tracer_provider
was replaced by get_tracer_provider
,
set_preferred_tracer_provider_implementation
was replaced by
set_tracer_provider
.
-
class
opentelemetry.trace.
Link
(context, attributes=None)[source]¶ Bases:
opentelemetry.trace.LinkBase
A link to a
Span
.- Parameters
-
class
opentelemetry.trace.
LazyLink
(context, link_formatter)[source]¶ Bases:
opentelemetry.trace.LinkBase
A lazy link to a
Span
.- Parameters
-
class
opentelemetry.trace.
SpanKind
[source]¶ Bases:
enum.Enum
Specifies additional details on how this span relates to its parent span.
Note that this enumeration is experimental and likely to change. See https://github.com/open-telemetry/opentelemetry-specification/pull/226.
-
INTERNAL
= 0¶
-
SERVER
= 1¶
-
CLIENT
= 2¶ Indicates that the span describes a request to some remote service.
-
PRODUCER
= 3¶ Indicates that the span describes a producer sending a message to a broker. Unlike client and server, there is usually no direct critical path latency relationship between producer and consumer spans.
-
CONSUMER
= 4¶ Indicates that the span describes a consumer receiving a message from a broker. Unlike client and server, there is usually no direct critical path latency relationship between producer and consumer spans.
-
-
class
opentelemetry.trace.
Span
[source]¶ Bases:
abc.ABC
A span represents a single operation within a trace.
-
abstract
end
(end_time=None)[source]¶ Sets the current time as the span’s end time.
The span’s end time is the wall time at which the operation finished.
Only the first call to
end
should modify the span, and implementations are free to ignore or raise on further calls.- Return type
None
-
abstract
get_context
()[source]¶ Gets the span’s SpanContext.
Get an immutable, serializable identifier for this span that can be used to create new child spans.
- Return type
- Returns
A
SpanContext
with a copy of this span’s immutable state.
-
abstract
set_attribute
(key, value)[source]¶ Sets an Attribute.
Sets a single Attribute with the key and value passed as arguments.
- Return type
None
-
abstract
add_event
(name, attributes=None, timestamp=None)[source]¶ Adds an
Event
.Adds a single
Event
with the name and, optionally, a timestamp and attributes passed as arguments. Implementations should generate a timestamp if thetimestamp
argument is omitted.- Return type
None
-
abstract
add_lazy_event
(name, event_formatter, timestamp=None)[source]¶ Adds an
Event
.Adds a single
Event
with the name, an event formatter that calculates the attributes lazily and, optionally, a timestamp. Implementations should generate a timestamp if thetimestamp
argument is omitted.- Return type
None
-
abstract
update_name
(name)[source]¶ Updates the
Span
name.This will override the name provided via
Tracer.start_span()
.Upon this update, any sampling behavior based on Span name will depend on the implementation.
- Return type
None
-
abstract
-
class
opentelemetry.trace.
TraceFlags
[source]¶ Bases:
int
A bitmask that represents options specific to the trace.
The only supported option is the “sampled” flag (
0x01
). If set, this flag indicates that the trace may have been sampled upstream.See the W3C Trace Context - Traceparent spec for details.
-
DEFAULT
= 0¶
-
SAMPLED
= 1¶
-
-
class
opentelemetry.trace.
TraceState
[source]¶ Bases:
dict
,typing.Generic
A list of key-value pairs representing vendor-specific trace info.
Keys and values are strings of up to 256 printable US-ASCII characters. Implementations should conform to the W3C Trace Context - Tracestate spec, which describes additional restrictions on valid field values.
-
class
opentelemetry.trace.
SpanContext
(trace_id, span_id, is_remote, trace_flags=0, trace_state={})[source]¶ Bases:
object
The state of a Span to propagate between processes.
This class includes the immutable attributes of a
Span
that must be propagated to a span’s children and across process boundaries.- Parameters
trace_id (
int
) – The ID of the trace that this span belongs to.span_id (
int
) – This span’s ID.trace_flags (
TraceFlags
) – Trace options to propagate.trace_state (
TraceState
) – Tracing-system-specific info to propagate.is_remote (
bool
) – True if propagated from a remote parent.
-
is_valid
()[source]¶ Get whether this
SpanContext
is valid.A
SpanContext
is said to be invalid if its trace ID or span ID is invalid (i.e.0
).- Return type
- Returns
True if the
SpanContext
is valid, false otherwise.
-
class
opentelemetry.trace.
DefaultSpan
(context)[source]¶ Bases:
opentelemetry.trace.Span
The default Span that is used when no Span implementation is available.
All operations are no-op except context propagation.
-
get_context
()[source]¶ Gets the span’s SpanContext.
Get an immutable, serializable identifier for this span that can be used to create new child spans.
- Return type
- Returns
A
SpanContext
with a copy of this span’s immutable state.
-
is_recording_events
()[source]¶ Returns whether this span will be recorded.
Returns true if this Span is active and recording information like events with the add_event operation and attributes using set_attribute.
- Return type
-
end
(end_time=None)[source]¶ Sets the current time as the span’s end time.
The span’s end time is the wall time at which the operation finished.
Only the first call to
end
should modify the span, and implementations are free to ignore or raise on further calls.- Return type
None
-
set_attribute
(key, value)[source]¶ Sets an Attribute.
Sets a single Attribute with the key and value passed as arguments.
- Return type
None
-
add_event
(name, attributes=None, timestamp=None)[source]¶ Adds an
Event
.Adds a single
Event
with the name and, optionally, a timestamp and attributes passed as arguments. Implementations should generate a timestamp if thetimestamp
argument is omitted.- Return type
None
-
add_lazy_event
(name, event_formatter, timestamp=None)[source]¶ Adds an
Event
.Adds a single
Event
with the name, an event formatter that calculates the attributes lazily and, optionally, a timestamp. Implementations should generate a timestamp if thetimestamp
argument is omitted.- Return type
None
-
update_name
(name)[source]¶ Updates the
Span
name.This will override the name provided via
Tracer.start_span()
.Upon this update, any sampling behavior based on Span name will depend on the implementation.
- Return type
None
-
-
class
opentelemetry.trace.
TracerProvider
[source]¶ Bases:
abc.ABC
-
abstract
get_tracer
(instrumenting_module_name, instrumenting_library_version='')[source]¶ Returns a
Tracer
for use by the given instrumentation library.For any two calls it is undefined whether the same or different
Tracer
instances are returned, even for different library names.This function may return different
Tracer
types (e.g. a no-op tracer vs. a functional tracer).- Parameters
instrumenting_module_name (
str
) –The name of the instrumenting module (usually just
__name__
).This should not be the name of the module that is instrumented but the name of the module doing the instrumentation. E.g., instead of
"requests"
, use"opentelemetry.ext.http_requests"
.instrumenting_library_version (
str
) – Optional. The version string of the instrumenting library. Usually this should be the same aspkg_resources.get_distribution(instrumenting_library_name).version
.
- Return type
-
abstract
-
class
opentelemetry.trace.
DefaultTracerProvider
[source]¶ Bases:
opentelemetry.trace.TracerProvider
The default TracerProvider, used when no implementation is available.
All operations are no-op.
-
get_tracer
(instrumenting_module_name, instrumenting_library_version='')[source]¶ Returns a
Tracer
for use by the given instrumentation library.For any two calls it is undefined whether the same or different
Tracer
instances are returned, even for different library names.This function may return different
Tracer
types (e.g. a no-op tracer vs. a functional tracer).- Parameters
instrumenting_module_name (
str
) –The name of the instrumenting module (usually just
__name__
).This should not be the name of the module that is instrumented but the name of the module doing the instrumentation. E.g., instead of
"requests"
, use"opentelemetry.ext.http_requests"
.instrumenting_library_version (
str
) – Optional. The version string of the instrumenting library. Usually this should be the same aspkg_resources.get_distribution(instrumenting_library_name).version
.
- Return type
-
-
class
opentelemetry.trace.
Tracer
[source]¶ Bases:
abc.ABC
Handles span creation and in-process context propagation.
This class provides methods for manipulating the context, creating spans, and controlling spans’ lifecycles.
-
CURRENT_SPAN
= <opentelemetry.trace.DefaultSpan object>¶
-
abstract
get_current_span
()[source]¶ Gets the currently active span from the context.
If there is no current span, return a placeholder span with an invalid context.
- Return type
- Returns
The currently active
Span
, or a placeholder span with an invalidSpanContext
.
-
abstract
start_span
(name, parent=<opentelemetry.trace.DefaultSpan object>, kind=<SpanKind.INTERNAL: 0>, attributes=None, links=(), start_time=None, set_status_on_exception=True)[source]¶ Starts a span.
Create a new span. Start the span without setting it as the current span in this tracer’s context.
By default the current span will be used as parent, but an explicit parent can also be specified, either a
Span
or aSpanContext
. If the specified value isNone
, the created span will be a root span.The span can be used as context manager. On exiting, the span will be ended.
Example:
# tracer.get_current_span() will be used as the implicit parent. # If none is found, the created span will be a root instance. with tracer.start_span("one") as child: child.add_event("child's event")
Applications that need to set the newly created span as the current instance should use
start_as_current_span()
instead.- Parameters
name (
str
) – The name of the span to be created.parent (
Union
[Span
,SpanContext
,None
]) – The span’s parent. Defaults to the current span.kind (
SpanKind
) – The span’s kind (relationship to parent). Note that is meaningful even if there is no parent.attributes (
Optional
[Dict
[str
,Union
[str
,bool
,int
,float
,Sequence
[str
],Sequence
[bool
],Sequence
[int
],Sequence
[float
]]]]) – The span’s attributes.set_status_on_exception (
bool
) – Only relevant if the returned span is used in a with/context manager. Defines wether the span status will be automatically set to UNKNOWN when an uncaught exception is raised in the span with block. The span status won’t be set by this mechanism if it was previousy set manually.
- Return type
- Returns
The newly-created span.
-
abstract
start_as_current_span
(name, parent=<opentelemetry.trace.DefaultSpan object>, kind=<SpanKind.INTERNAL: 0>, attributes=None, links=())[source]¶ Context manager for creating a new span and set it as the current span in this tracer’s context.
On exiting the context manager stops the span and set its parent as the current span.
Example:
with tracer.start_as_current_span("one") as parent: parent.add_event("parent's event") with tracer.start_as_current_span("two") as child: child.add_event("child's event") tracer.get_current_span() # returns child tracer.get_current_span() # returns parent tracer.get_current_span() # returns previously active span
This is a convenience method for creating spans attached to the tracer’s context. Applications that need more control over the span lifetime should use
start_span()
instead. For example:with tracer.start_as_current_span(name) as span: do_work()
is equivalent to:
span = tracer.start_span(name) with tracer.use_span(span, end_on_exit=True): do_work()
- Parameters
name (
str
) – The name of the span to be created.parent (
Union
[Span
,SpanContext
,None
]) – The span’s parent. Defaults to the current span.kind (
SpanKind
) – The span’s kind (relationship to parent). Note that is meaningful even if there is no parent.attributes (
Optional
[Dict
[str
,Union
[str
,bool
,int
,float
,Sequence
[str
],Sequence
[bool
],Sequence
[int
],Sequence
[float
]]]]) – The span’s attributes.
- Yields
The newly-created span.
- Return type
-
abstract
use_span
(span, end_on_exit=False)[source]¶ Context manager for controlling a span’s lifetime.
Set the given span as the current span in this tracer’s context.
On exiting the context manager set the span that was previously active as the current span (this is usually but not necessarily the parent of the given span). If
end_on_exit
isTrue
, then the span is also ended when exiting the context manager.
-
-
class
opentelemetry.trace.
DefaultTracer
[source]¶ Bases:
opentelemetry.trace.Tracer
The default Tracer, used when no Tracer implementation is available.
All operations are no-op.
-
get_current_span
()[source]¶ Gets the currently active span from the context.
If there is no current span, return a placeholder span with an invalid context.
- Return type
- Returns
The currently active
Span
, or a placeholder span with an invalidSpanContext
.
-
start_span
(name, parent=<opentelemetry.trace.DefaultSpan object>, kind=<SpanKind.INTERNAL: 0>, attributes=None, links=(), start_time=None, set_status_on_exception=True)[source]¶ Starts a span.
Create a new span. Start the span without setting it as the current span in this tracer’s context.
By default the current span will be used as parent, but an explicit parent can also be specified, either a
Span
or aSpanContext
. If the specified value isNone
, the created span will be a root span.The span can be used as context manager. On exiting, the span will be ended.
Example:
# tracer.get_current_span() will be used as the implicit parent. # If none is found, the created span will be a root instance. with tracer.start_span("one") as child: child.add_event("child's event")
Applications that need to set the newly created span as the current instance should use
start_as_current_span()
instead.- Parameters
name (
str
) – The name of the span to be created.parent (
Union
[Span
,SpanContext
,None
]) – The span’s parent. Defaults to the current span.kind (
SpanKind
) – The span’s kind (relationship to parent). Note that is meaningful even if there is no parent.attributes (
Optional
[Dict
[str
,Union
[str
,bool
,int
,float
,Sequence
[str
],Sequence
[bool
],Sequence
[int
],Sequence
[float
]]]]) – The span’s attributes.set_status_on_exception (
bool
) – Only relevant if the returned span is used in a with/context manager. Defines wether the span status will be automatically set to UNKNOWN when an uncaught exception is raised in the span with block. The span status won’t be set by this mechanism if it was previousy set manually.
- Return type
- Returns
The newly-created span.
-
start_as_current_span
(name, parent=<opentelemetry.trace.DefaultSpan object>, kind=<SpanKind.INTERNAL: 0>, attributes=None, links=())[source]¶ Context manager for creating a new span and set it as the current span in this tracer’s context.
On exiting the context manager stops the span and set its parent as the current span.
Example:
with tracer.start_as_current_span("one") as parent: parent.add_event("parent's event") with tracer.start_as_current_span("two") as child: child.add_event("child's event") tracer.get_current_span() # returns child tracer.get_current_span() # returns parent tracer.get_current_span() # returns previously active span
This is a convenience method for creating spans attached to the tracer’s context. Applications that need more control over the span lifetime should use
start_span()
instead. For example:with tracer.start_as_current_span(name) as span: do_work()
is equivalent to:
span = tracer.start_span(name) with tracer.use_span(span, end_on_exit=True): do_work()
- Parameters
name (
str
) – The name of the span to be created.parent (
Union
[Span
,SpanContext
,None
]) – The span’s parent. Defaults to the current span.kind (
SpanKind
) – The span’s kind (relationship to parent). Note that is meaningful even if there is no parent.attributes (
Optional
[Dict
[str
,Union
[str
,bool
,int
,float
,Sequence
[str
],Sequence
[bool
],Sequence
[int
],Sequence
[float
]]]]) – The span’s attributes.
- Yields
The newly-created span.
- Return type
-
use_span
(span, end_on_exit=False)[source]¶ Context manager for controlling a span’s lifetime.
Set the given span as the current span in this tracer’s context.
On exiting the context manager set the span that was previously active as the current span (this is usually but not necessarily the parent of the given span). If
end_on_exit
isTrue
, then the span is also ended when exiting the context manager.
-
-
opentelemetry.trace.
get_tracer
(instrumenting_module_name, instrumenting_library_version='', tracer_provider=None)[source]¶ Returns a
Tracer
for use by the given instrumentation library.This function is a convenience wrapper for opentelemetry.trace.TracerProvider.get_tracer.
If tracer_provider is ommited the current configured one is used.
- Return type
-
opentelemetry.trace.
set_tracer_provider
(tracer_provider)[source]¶ Sets the current global
TracerProvider
object.- Return type
None
-
opentelemetry.trace.
get_tracer_provider
()[source]¶ Gets the current global
TracerProvider
object.- Return type