opentelemetry.trace package
Submodules
- opentelemetry.trace.status
- opentelemetry.trace.span
Span
TraceFlags
TraceState
SpanContext
NonRecordingSpan
NonRecordingSpan.get_span_context()
NonRecordingSpan.is_recording()
NonRecordingSpan.end()
NonRecordingSpan.set_attributes()
NonRecordingSpan.set_attribute()
NonRecordingSpan.add_event()
NonRecordingSpan.add_link()
NonRecordingSpan.update_name()
NonRecordingSpan.set_status()
NonRecordingSpan.record_exception()
format_trace_id()
format_span_id()
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 NonRecordingSpan
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.NonRecordingSpan(context)[source]
Bases:
Span
The 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:
- set_attributes(attributes)[source]
Sets Attributes.
Sets Attributes with the key and value passed as arguments dict.
Note: The behavior of None value attributes is undefined, and hence strongly discouraged. It is also preferred to set attributes at span creation, instead of calling this method later since samplers can only consider information already present during span creation.
- Return type:
- set_attribute(key, value)[source]
Sets an Attribute.
Sets a single Attribute with the key and value passed as arguments.
Note: The behavior of None value attributes is undefined, and hence strongly discouraged. It is also preferred to set attributes at span creation, instead of calling this method later since samplers can only consider information already present during span creation.
- Return type:
- 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 the timestamp argument is omitted.
- Return type:
- add_link(context, attributes=None)[source]
Adds a Link.
Adds a single Link with the SpanContext of the span to link to and, optionally, attributes passed as arguments. Implementations may ignore calls with an invalid span context if both attributes and TraceState are empty.
Note: It is preferred to add links at span creation, instead of calling this method later since samplers can only consider information already present during span creation.
- Return type:
- 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:
- class opentelemetry.trace.Link(context, attributes=None)[source]
Bases:
_LinkBase
A link to a Span. The attributes of a Link are immutable.
- Parameters:
- class opentelemetry.trace.Span[source]
Bases:
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:
- 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_attributes(attributes)[source]
Sets Attributes.
Sets Attributes with the key and value passed as arguments dict.
Note: The behavior of None value attributes is undefined, and hence strongly discouraged. It is also preferred to set attributes at span creation, instead of calling this method later since samplers can only consider information already present during span creation.
- Return type:
- abstract set_attribute(key, value)[source]
Sets an Attribute.
Sets a single Attribute with the key and value passed as arguments.
Note: The behavior of None value attributes is undefined, and hence strongly discouraged. It is also preferred to set attributes at span creation, instead of calling this method later since samplers can only consider information already present during span creation.
- Return type:
- 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 the timestamp argument is omitted.
- Return type:
- add_link(context, attributes=None)[source]
Adds a Link.
Adds a single Link with the SpanContext of the span to link to and, optionally, attributes passed as arguments. Implementations may ignore calls with an invalid span context if both attributes and TraceState are empty.
Note: It is preferred to add links at span creation, instead of calling this method later since samplers can only consider information already present during span creation.
- Return type:
- 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:
- 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:
- class opentelemetry.trace.SpanContext(trace_id: int, span_id: int, is_remote: bool, trace_flags: TraceFlags | None = 0, trace_state: TraceState | None = [])[source]
Bases:
Tuple
[int
,int
,bool
,TraceFlags
,TraceState
,bool
]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.
is_remote – True if propagated from a remote parent.
trace_flags – Trace options to propagate.
trace_state – Tracing-system-specific info to propagate.
- property trace_flags: TraceFlags
- property trace_state: TraceState
- class opentelemetry.trace.SpanKind(value)[source]
Bases:
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.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(entries=None)[source]
-
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.
- add(key, value)[source]
Adds a key-value pair to tracestate. The provided pair should adhere to w3c tracestate identifiers format.
- Parameters:
- Return type:
- Returns:
A new TraceState with the modifications applied.
If the provided key-value pair is invalid or results in tracestate that violates tracecontext specification, they are discarded and same tracestate will be returned.
- update(key, value)[source]
Updates a key-value pair in tracestate. The provided pair should adhere to w3c tracestate identifiers format.
- Parameters:
- Return type:
- Returns:
A new TraceState with the modifications applied.
If the provided key-value pair is invalid or results in tracestate that violates tracecontext specification, they are discarded and same tracestate will be returned.
- delete(key)[source]
Deletes a key-value from tracestate.
- Parameters:
key (
str
) – A valid tracestate key to remove key-value pair from tracestate- Return type:
- Returns:
A new TraceState with the modifications applied.
If the provided key-value pair is invalid or results in tracestate that violates tracecontext specification, they are discarded and same tracestate will be returned.
- to_header()[source]
Creates a w3c tracestate header from a TraceState.
- Return type:
- Returns:
A string that adheres to the w3c tracestate header format.
- classmethod from_header(header_list)[source]
Parses one or more w3c tracestate header into a TraceState.
- Parameters:
header_list (
List
[str
]) – one or more w3c tracestate headers.- Return type:
- Returns:
A valid TraceState that contains values extracted from the tracestate header.
If the format of one headers is illegal, all values will be discarded and an empty tracestate will be returned.
If the number of keys is beyond the maximum, all values will be discarded and an empty tracestate will be returned.
- class opentelemetry.trace.TracerProvider[source]
Bases:
ABC
- abstract get_tracer(instrumenting_module_name, instrumenting_library_version=None, schema_url=None, attributes=None)[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 uniquely identifiable name for instrumentation scope, such as instrumentation library, package, module or class name.
__name__
may not be used as this can result in different tracer names if the tracers are in different files. It is better to use a fixed string that can be imported where needed and used consistently as the name of the tracer.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 (
Optional
[str
]) – Optional. The version string of the instrumenting library. Usually this should be the same asimportlib.metadata.version(instrumenting_library_name)
.schema_url (
Optional
[str
]) – Optional. Specifies the Schema URL of the emitted telemetry.attributes (
Optional
[Mapping
[str
,Union
[str
,bool
,int
,float
,Sequence
[str
],Sequence
[bool
],Sequence
[int
],Sequence
[float
]]]]) – Optional. Specifies the attributes of the emitted telemetry.
- Return type:
- class opentelemetry.trace.Tracer[source]
Bases:
ABC
Handles span creation and in-process context propagation.
This class provides methods for manipulating the context, creating spans, and controlling spans’ lifecycles.
- abstract start_span(name, context=None, kind=SpanKind.INTERNAL, attributes=None, links=None, start_time=None, record_exception=True, 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 current Span. If there is no current span in the global Context 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
[str
],Sequence
[bool
],Sequence
[int
],Sequence
[float
]]]]) – The span’s attributes.links (
Optional
[Sequence
[Link
]]) – Links span to other spansrecord_exception (
bool
) – Whether to record any exceptions raised within the context as error event on the span.set_status_on_exception (
bool
) – Only relevant if the returned span is used in a with/context manager. Defines whether 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, attributes=None, links=None, start_time=None, record_exception=True, set_status_on_exception=True, end_on_exit=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 its 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 tracer.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 opentelemetry.trace.use_span(span, end_on_exit=True): do_work()
This can also be used as a decorator:
@tracer.start_as_current_span("name") def function(): ... function()
- 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
[str
],Sequence
[bool
],Sequence
[int
],Sequence
[float
]]]]) – The span’s attributes.links (
Optional
[Sequence
[Link
]]) – Links span to other spansrecord_exception (
bool
) – Whether to record any exceptions raised within the context as error event on the span.set_status_on_exception (
bool
) – Only relevant if the returned span is used in a with/context manager. Defines whether 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.end_on_exit (
bool
) – Whether to end the span automatically when leaving the context manager.
- Yields:
The newly-created span.
- Return type:
- opentelemetry.trace.format_span_id(span_id)[source]
Convenience span ID formatting method :type span_id:
int
:param span_id: Span ID int- Return type:
- Returns:
The span ID as 16-byte hexadecimal string
- opentelemetry.trace.format_trace_id(trace_id)[source]
Convenience trace ID formatting method :type trace_id:
int
:param trace_id: Trace ID int- Return type:
- Returns:
The trace ID as 32-byte hexadecimal string
- opentelemetry.trace.get_tracer(instrumenting_module_name, instrumenting_library_version=None, tracer_provider=None, schema_url=None, attributes=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 omitted the current configured one is used.
- Return type:
- opentelemetry.trace.get_tracer_provider()[source]
Gets the current global
TracerProvider
object.- 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 further attempt is made.
- Return type:
- opentelemetry.trace.set_span_in_context(span, context=None)[source]
Set the span in the given context.
- opentelemetry.trace.use_span(span, end_on_exit=False, record_exception=True, set_status_on_exception=True)[source]
Takes a non-active span and activates it in the current context.
- Parameters:
span (
Span
) – The span that should be activated in the current context.end_on_exit (
bool
) – Whether to end the span automatically when leaving the context manager scope.record_exception (
bool
) – Whether to record any exceptions raised within the context as error event on the span.set_status_on_exception (
bool
) – Only relevant if the returned span is used in a with/context manager. Defines whether 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:
- class opentelemetry.trace.Status(status_code=StatusCode.UNSET, 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: StatusCode
Represents the canonical status code of a finished Span.
- class opentelemetry.trace.StatusCode(value)[source]
Bases:
Enum
Represents the canonical set of status codes of a finished Span.
- UNSET = 0
The default status.
- OK = 1
The operation has been validated by an Application developer or Operator to have completed successfully.
- ERROR = 2
The operation contains an error.