opentelemetry.sdk.trace package

Submodules

class opentelemetry.sdk.trace.SpanProcessor[source]

Bases: object

Interface which allows hooks for SDK’s Span start and end method invocations.

Span processors can be registered directly using TracerProvider.add_span_processor() and they are invoked in the same order as they were registered.

on_start(span, parent_context=None)[source]

Called when a opentelemetry.trace.Span is started.

This method is called synchronously on the thread that starts the span, therefore it should not block or throw an exception.

Parameters:
Return type:

None

on_end(span)[source]

Called when a opentelemetry.trace.Span is ended.

This method is called synchronously on the thread that ends the span, therefore it should not block or throw an exception.

Parameters:

span (ReadableSpan) – The opentelemetry.trace.Span that just ended.

Return type:

None

shutdown()[source]

Called when a opentelemetry.sdk.trace.TracerProvider is shutdown.

Return type:

None

force_flush(timeout_millis=30000)[source]

Export all ended spans to the configured Exporter that have not yet been exported.

Parameters:

timeout_millis (int) – The maximum amount of time to wait for spans to be exported.

Return type:

bool

Returns:

False if the timeout is exceeded, True otherwise.

class opentelemetry.sdk.trace.SynchronousMultiSpanProcessor[source]

Bases: SpanProcessor

Implementation of class:SpanProcessor that forwards all received events to a list of span processors sequentially.

The underlying span processors are called in sequential order as they were added.

add_span_processor(span_processor)[source]

Adds a SpanProcessor to the list handled by this instance.

Return type:

None

on_start(span, parent_context=None)[source]

Called when a opentelemetry.trace.Span is started.

This method is called synchronously on the thread that starts the span, therefore it should not block or throw an exception.

Parameters:
Return type:

None

on_end(span)[source]

Called when a opentelemetry.trace.Span is ended.

This method is called synchronously on the thread that ends the span, therefore it should not block or throw an exception.

Parameters:

span (ReadableSpan) – The opentelemetry.trace.Span that just ended.

Return type:

None

shutdown()[source]

Sequentially shuts down all underlying span processors.

Return type:

None

force_flush(timeout_millis=30000)[source]

Sequentially calls force_flush on all underlying SpanProcessor

Parameters:

timeout_millis (int) – The maximum amount of time over all span processors to wait for spans to be exported. In case the first n span processors exceeded the timeout followup span processors will be skipped.

Return type:

bool

Returns:

True if all span processors flushed their spans within the given timeout, False otherwise.

class opentelemetry.sdk.trace.ConcurrentMultiSpanProcessor(num_threads=2)[source]

Bases: SpanProcessor

Implementation of SpanProcessor that forwards all received events to a list of span processors in parallel.

Calls to the underlying span processors are forwarded in parallel by submitting them to a thread pool executor and waiting until each span processor finished its work.

Parameters:

num_threads (int) – The number of threads managed by the thread pool executor and thus defining how many span processors can work in parallel.

add_span_processor(span_processor)[source]

Adds a SpanProcessor to the list handled by this instance.

Return type:

None

on_start(span, parent_context=None)[source]

Called when a opentelemetry.trace.Span is started.

This method is called synchronously on the thread that starts the span, therefore it should not block or throw an exception.

Parameters:
Return type:

None

on_end(span)[source]

Called when a opentelemetry.trace.Span is ended.

This method is called synchronously on the thread that ends the span, therefore it should not block or throw an exception.

Parameters:

span (ReadableSpan) – The opentelemetry.trace.Span that just ended.

Return type:

None

shutdown()[source]

Shuts down all underlying span processors in parallel.

Return type:

None

force_flush(timeout_millis=30000)[source]

Calls force_flush on all underlying span processors in parallel.

Parameters:

timeout_millis (int) – The maximum amount of time to wait for spans to be exported.

Return type:

bool

Returns:

True if all span processors flushed their spans within the given timeout, False otherwise.

class opentelemetry.sdk.trace.EventBase(name, timestamp=None)[source]

Bases: ABC

property name: str
property timestamp: int
abstract property attributes: Mapping[str, str | bool | int | float | Sequence[str] | Sequence[bool] | Sequence[int] | Sequence[float]] | None
class opentelemetry.sdk.trace.Event(name, attributes=None, timestamp=None, limit=128)[source]

Bases: EventBase

A text annotation with a set of attributes. The attributes of an event are immutable.

Parameters:
property attributes: Mapping[str, str | bool | int | float | Sequence[str] | Sequence[bool] | Sequence[int] | Sequence[float]] | None
class opentelemetry.sdk.trace.ReadableSpan(name, context=None, parent=None, resource=None, attributes=None, events=(), links=(), kind=SpanKind.INTERNAL, instrumentation_info=None, status=<opentelemetry.trace.status.Status object>, start_time=None, end_time=None, instrumentation_scope=None)[source]

Bases: object

Provides read-only access to span attributes.

Users should NOT be creating these objects directly. ReadableSpan`s are created as a direct result from using the tracing pipeline via the `Tracer.

property dropped_attributes: int
property dropped_events: int
property name: str
get_span_context()[source]
property context
property kind: SpanKind
property parent: SpanContext | None
property start_time: int | None
property end_time: int | None
property status: Status
property attributes: Mapping[str, str | bool | int | float | Sequence[str] | Sequence[bool] | Sequence[int] | Sequence[float]] | None
property events: Sequence[Event]
property resource: Resource
property instrumentation_info: InstrumentationInfo | None
property instrumentation_scope: InstrumentationScope | None
to_json(indent=4)[source]
class opentelemetry.sdk.trace.SpanLimits(max_attributes=None, max_events=None, max_links=None, max_span_attributes=None, max_event_attributes=None, max_link_attributes=None, max_attribute_length=None, max_span_attribute_length=None)[source]

Bases: object

The limits that should be enforce on recorded data such as events, links, attributes etc.

This class does not enforce any limits itself. It only provides an a way read limits from env, default values and from user provided arguments.

All limit arguments must be either a non-negative integer, None or SpanLimits.UNSET.

  • All limit arguments are optional.

  • If a limit argument is not set, the class will try to read its value from the corresponding environment variable.

  • If the environment variable is not set, the default value, if any, will be used.

Limit precedence:

  • If a model specific limit is set, it will be used.

  • Else if the corresponding global limit is set, it will be used.

  • Else if the model specific limit has a default value, the default value will be used.

  • Else if the global limit has a default value, the default value will be used.

Parameters:
  • max_attributes (Optional[int]) – Maximum number of attributes that can be added to a span, event, and link. Environment variable: OTEL_ATTRIBUTE_COUNT_LIMIT Default: {_DEFAULT_ATTRIBUTE_COUNT_LIMIT}

  • max_events (Optional[int]) – Maximum number of events that can be added to a Span. Environment variable: OTEL_SPAN_EVENT_COUNT_LIMIT Default: {_DEFAULT_SPAN_EVENT_COUNT_LIMIT}

  • max_links (Optional[int]) – Maximum number of links that can be added to a Span. Environment variable: OTEL_SPAN_LINK_COUNT_LIMIT Default: {_DEFAULT_SPAN_LINK_COUNT_LIMIT}

  • max_span_attributes (Optional[int]) – Maximum number of attributes that can be added to a Span. Environment variable: OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT Default: {_DEFAULT_OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT}

  • max_event_attributes (Optional[int]) – Maximum number of attributes that can be added to an Event. Default: {_DEFAULT_OTEL_EVENT_ATTRIBUTE_COUNT_LIMIT}

  • max_link_attributes (Optional[int]) – Maximum number of attributes that can be added to a Link. Default: {_DEFAULT_OTEL_LINK_ATTRIBUTE_COUNT_LIMIT}

  • max_attribute_length (Optional[int]) – Maximum length an attribute value can have. Values longer than the specified length will be truncated.

  • max_span_attribute_length (Optional[int]) – Maximum length a span attribute value can have. Values longer than the specified length will be truncated.

UNSET = -1
class opentelemetry.sdk.trace.Span(name, context, parent=None, sampler=None, trace_config=None, resource=None, attributes=None, events=None, links=(), kind=SpanKind.INTERNAL, span_processor=<opentelemetry.sdk.trace.SpanProcessor object>, instrumentation_info=None, record_exception=True, set_status_on_exception=True, limits=SpanLimits(max_span_attributes=None, max_events_attributes=None, max_link_attributes=None, max_attributes=128, max_events=None, max_links=None, max_attribute_length=None), instrumentation_scope=None)[source]

Bases: Span, ReadableSpan

See opentelemetry.trace.Span.

Users should create Span objects via the Tracer instead of this constructor.

Parameters:
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.

Returns:

A opentelemetry.trace.SpanContext with a copy of this span’s immutable state.

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:

None

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:

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 the timestamp argument is omitted.

Return type:

None

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.

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:

None

start(start_time=None, parent_context=None)[source]
Return type:

None

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

update_name(*args, **kwargs)[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.

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:

bool

set_status(*args, **kwargs)[source]

Sets the Status of the Span. If used, this will override the default Span status.

record_exception(exception, attributes=None, timestamp=None, escaped=False)[source]

Records an exception as a span event.

Return type:

None

class opentelemetry.sdk.trace.Tracer(sampler, resource, span_processor, id_generator, instrumentation_info, span_limits, instrumentation_scope)[source]

Bases: Tracer

See opentelemetry.trace.Tracer.

start_as_current_span(name, context=None, kind=SpanKind.INTERNAL, attributes=None, links=(), 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 spans

  • start_time (Optional[int]) – Sets the start time of a span

  • 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.

  • end_on_exit (bool) – Whether to end the span automatically when leaving the context manager.

Yields:

The newly-created span.

Return type:

Iterator[Span]

start_span(name, context=None, kind=SpanKind.INTERNAL, attributes=None, links=(), 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 spans

  • start_time (Optional[int]) – Sets the start time of a span

  • 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:

Span

Returns:

The newly-created span.

class opentelemetry.sdk.trace.TracerProvider(sampler=None, resource=None, shutdown_on_exit=True, active_span_processor=None, id_generator=None, span_limits=None)[source]

Bases: TracerProvider

See opentelemetry.trace.TracerProvider.

property resource: Resource
get_tracer(instrumenting_module_name, instrumenting_library_version=None, schema_url=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 as importlib.metadata.version(instrumenting_library_name).

  • schema_url (Optional[str]) – Optional. Specifies the Schema URL of the emitted telemetry.

Return type:

Tracer

add_span_processor(span_processor)[source]

Registers a new SpanProcessor for this TracerProvider.

The span processors are invoked in the same order they are registered.

Return type:

None

shutdown()[source]

Shut down the span processors added to the tracer provider.

force_flush(timeout_millis=30000)[source]

Requests the active span processor to process all spans that have not yet been processed.

By default force flush is called sequentially on all added span processors. This means that span processors further back in the list have less time to flush their spans. To have span processors flush their spans in parallel it is possible to initialize the tracer provider with an instance of ConcurrentMultiSpanProcessor at the cost of using multiple threads.

Parameters:

timeout_millis (int) – The maximum amount of time to wait for spans to be processed.

Return type:

bool

Returns:

False if the timeout is exceeded, True otherwise.