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 is done via the Context
from opentelemetry.trace import set_span_in_context
context = set_span_in_context(parent)
child = tracer.start_span("child", context=context)
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.
IdsGenerator
[source]¶ Bases:
abc.ABC
-
abstract
generate_span_id
()[source]¶ Get a new span ID.
- Return type
- Returns
A 64-bit int for use as a span ID
-
abstract
generate_trace_id
()[source]¶ Get a new trace ID.
Implementations should at least make the 64 least significant bits uniformly random. Samplers like the
TraceIdRatioBased
sampler rely on this randomness to make sampling decisions.See the specification on TraceIdRatioBased.
- Return type
- Returns
A 128-bit int for use as a trace ID
-
abstract
-
class
opentelemetry.trace.
RandomIdsGenerator
[source]¶ Bases:
opentelemetry.trace.ids_generator.IdsGenerator
The default IDs generator for TracerProvider which randomly generates all bits when generating IDs.
-
generate_span_id
()[source]¶ Get a new span ID.
- Return type
- Returns
A 64-bit int for use as a span ID
-
generate_trace_id
()[source]¶ Get a new trace ID.
Implementations should at least make the 64 least significant bits uniformly random. Samplers like the
TraceIdRatioBased
sampler rely on this randomness to make sampling decisions.See the specification on TraceIdRatioBased.
- Return type
- Returns
A 128-bit int for use as a trace ID
-
-
opentelemetry.trace.
set_span_in_context
(span, context=None)[source]¶ Set the span in the given context.
-
class
opentelemetry.trace.
DefaultSpan
(context)[source]¶ Bases:
opentelemetry.trace.span.Span
The default Span that is used when no Span implementation is available.
All operations are no-op except context propagation.
-
get_span_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
opentelemetry.trace.SpanContext
with a copy of this span’s immutable state.
-
is_recording
()[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
-
update_name
(name)[source]¶ Updates the
Span
name.This will override the name provided via
opentelemetry.trace.Tracer.start_span()
.Upon this update, any sampling behavior based on Span name will depend on the implementation.
- Return type
None
-
-
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_span_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
opentelemetry.trace.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
update_name
(name)[source]¶ Updates the
Span
name.This will override the name provided via
opentelemetry.trace.Tracer.start_span()
.Upon this update, any sampling behavior based on Span name will depend on the implementation.
- Return type
None
-
abstract
is_recording
()[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
-
abstract
-
class
opentelemetry.trace.
SpanContext
[source]¶ Bases:
tuple
,typing.Generic
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 – The ID of the trace that this span belongs to.
span_id – This span’s ID.
trace_flags – Trace options to propagate.
trace_state – Tracing-system-specific info to propagate.
is_remote – True if propagated from a remote parent.
-
property
trace_flags
¶ - Return type
-
property
trace_state
¶ - Return type
-
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.
Status
(status_code=<StatusCode.UNSET: 1>, description=None)[source]¶ Bases:
object
Represents the status of a finished Span.
- Parameters
status_code (
StatusCode
) – The canonical status code that describes the result status of the operation.description (
Optional
[str
]) – An optional description of the status.
-
property
status_code
¶ Represents the canonical status code of a finished Span.
- Return type
-
class
opentelemetry.trace.
Link
(context, attributes=None)[source]¶ Bases:
opentelemetry.trace.LinkBase
A 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.
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.instrumentation.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.instrumentation.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.span.DefaultSpan object>¶
-
abstract
start_span
(name, context=None, 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 the context. To start the span and use the context in a single method, see
start_as_current_span()
.By default the current span in the context will be used as parent, but an explicit context can also be specified, by passing in a
Context
containing a currentSpan
. If there is no current span in the globalContext
or in the specified context, the created span will be a root span.The span can be used as a context manager. On exiting the context manager, the span’s end() method will be called.
Example:
# trace.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")
- Parameters
name (
str
) – The name of the span to be created.context (
Optional
[Context
]) – An optional Context containing the span’s parent. Defaults to the global context.kind (
SpanKind
) – The span’s kind (relationship to parent). Note that is meaningful even if there is no parent.attributes (
Optional
[Mapping
[str
,Union
[str
,bool
,int
,float
,Sequence
[Optional
[str
]],Sequence
[Optional
[bool
]],Sequence
[Optional
[int
]],Sequence
[Optional
[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 ERROR when an uncaught exception is raised in the span with block. The span status won’t be set by this mechanism if it was previously set manually.
- Return type
- Returns
The newly-created span.
-
abstract
start_as_current_span
(name, context=None, kind=<SpanKind.INTERNAL: 0>, attributes=None, links=(), record_exception=True)[source]¶ Context manager for creating a new span and set it as the current span in this tracer’s context.
Exiting the context manager will call the span’s end method, as well as return the current span to it’s previous value by returning to the previous context.
Example:
with tracer.start_as_current_span("one") as parent: parent.add_event("parent's event") with trace.start_as_current_span("two") as child: child.add_event("child's event") trace.get_current_span() # returns child trace.get_current_span() # returns parent trace.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.context (
Optional
[Context
]) – An optional Context containing the span’s parent. Defaults to the global context.kind (
SpanKind
) – The span’s kind (relationship to parent). Note that is meaningful even if there is no parent.attributes (
Optional
[Mapping
[str
,Union
[str
,bool
,int
,float
,Sequence
[Optional
[str
]],Sequence
[Optional
[bool
]],Sequence
[Optional
[int
]],Sequence
[Optional
[float
]]]]]) – The span’s attributes.record_exception (
bool
) – Whether to record any exceptions raised within the context as error event on the span.
- Yields
The newly-created span.
- Return type
-
abstract
use_span
(span, end_on_exit=False, record_exception=True)[source]¶ Context manager for setting the passed span as the current span in the context, as well as resetting the context back upon exiting the context manager.
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.
-
start_span
(name, context=None, 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 the context. To start the span and use the context in a single method, see
start_as_current_span()
.By default the current span in the context will be used as parent, but an explicit context can also be specified, by passing in a
Context
containing a currentSpan
. If there is no current span in the globalContext
or in the specified context, the created span will be a root span.The span can be used as a context manager. On exiting the context manager, the span’s end() method will be called.
Example:
# trace.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")
- Parameters
name (
str
) – The name of the span to be created.context (
Optional
[Context
]) – An optional Context containing the span’s parent. Defaults to the global context.kind (
SpanKind
) – The span’s kind (relationship to parent). Note that is meaningful even if there is no parent.attributes (
Optional
[Mapping
[str
,Union
[str
,bool
,int
,float
,Sequence
[Optional
[str
]],Sequence
[Optional
[bool
]],Sequence
[Optional
[int
]],Sequence
[Optional
[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 ERROR when an uncaught exception is raised in the span with block. The span status won’t be set by this mechanism if it was previously set manually.
- Return type
- Returns
The newly-created span.
-
start_as_current_span
(name, context=None, kind=<SpanKind.INTERNAL: 0>, attributes=None, links=(), record_exception=True)[source]¶ Context manager for creating a new span and set it as the current span in this tracer’s context.
Exiting the context manager will call the span’s end method, as well as return the current span to it’s previous value by returning to the previous context.
Example:
with tracer.start_as_current_span("one") as parent: parent.add_event("parent's event") with trace.start_as_current_span("two") as child: child.add_event("child's event") trace.get_current_span() # returns child trace.get_current_span() # returns parent trace.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.context (
Optional
[Context
]) – An optional Context containing the span’s parent. Defaults to the global context.kind (
SpanKind
) – The span’s kind (relationship to parent). Note that is meaningful even if there is no parent.attributes (
Optional
[Mapping
[str
,Union
[str
,bool
,int
,float
,Sequence
[Optional
[str
]],Sequence
[Optional
[bool
]],Sequence
[Optional
[int
]],Sequence
[Optional
[float
]]]]]) – The span’s attributes.record_exception (
bool
) – Whether to record any exceptions raised within the context as error event on the span.
- Yields
The newly-created span.
- Return type
-
use_span
(span, end_on_exit=False, record_exception=True)[source]¶ Context manager for setting the passed span as the current span in the context, as well as resetting the context back upon exiting the context manager.
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.This can only be done once, a warning will be logged if any furter attempt is made.
- Return type
None
-
opentelemetry.trace.
get_tracer_provider
()[source]¶ Gets the current global
TracerProvider
object.- Return type