# opentelemetry.sdk.trace package

## Submodules

- opentelemetry.sdk.trace.export
  - `SpanExportResult`
    - `SpanExportResult.SUCCESS`
    - `SpanExportResult.FAILURE`
  - `SpanExporter`
    - `SpanExporter.export()`
    - `SpanExporter.shutdown()`
    - `SpanExporter.force_flush()`
  - `SimpleSpanProcessor`
    - `SimpleSpanProcessor.on_start()`
    - `SimpleSpanProcessor.on_end()`
    - `SimpleSpanProcessor.shutdown()`
    - `SimpleSpanProcessor.force_flush()`
  - `BatchSpanProcessor`
    - `BatchSpanProcessor.span_exporter`
    - `BatchSpanProcessor.on_start()`
    - `BatchSpanProcessor.on_end()`
    - `BatchSpanProcessor.shutdown()`
    - `BatchSpanProcessor.force_flush()`
  - `ConsoleSpanExporter`
    - `ConsoleSpanExporter.export()`
    - `ConsoleSpanExporter.force_flush()`
- opentelemetry.sdk.trace.id_generator
  - `IdGenerator`
    - `IdGenerator.generate_span_id()`
    - `IdGenerator.generate_trace_id()`
  - `RandomIdGenerator`
    - `RandomIdGenerator.generate_span_id()`
    - `RandomIdGenerator.generate_trace_id()`
- opentelemetry.sdk.trace.sampling
  - `Decision`
    - `Decision.DROP`
    - `Decision.RECORD_ONLY`
    - `Decision.RECORD_AND_SAMPLE`
    - `Decision.is_recording()`
    - `Decision.is_sampled()`
  - `SamplingResult`
  - `Sampler`
    - `Sampler.should_sample()`
    - `Sampler.get_description()`
  - `StaticSampler`
    - `StaticSampler.should_sample()`
    - `StaticSampler.get_description()`
  - `ALWAYS_OFF`
  - `ALWAYS_ON`
  - `TraceIdRatioBased`
    - `TraceIdRatioBased.TRACE_ID_LIMIT`
    - `TraceIdRatioBased.get_bound_for_rate()`
    - `TraceIdRatioBased.rate`
    - `TraceIdRatioBased.bound`
    - `TraceIdRatioBased.should_sample()`
    - `TraceIdRatioBased.get_description()`
  - `ParentBased`
    - `ParentBased.should_sample()`
    - `ParentBased.get_description()`
  - `DEFAULT_OFF`
  - `DEFAULT_ON`
  - `ParentBasedTraceIdRatio`
- opentelemetry.sdk.util.instrumentation
  - `InstrumentationInfo`
    - `InstrumentationInfo.schema_url`
    - `InstrumentationInfo.version`
    - `InstrumentationInfo.name`
  - `InstrumentationScope`
    - `InstrumentationScope.schema_url`
    - `InstrumentationScope.version`
    - `InstrumentationScope.name`
    - `InstrumentationScope.attributes`
    - `InstrumentationScope.to_json()`

class opentelemetry.sdk.trace.SpanProcessor

  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)

    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:

      - span (`Span`) – The `opentelemetry.trace.Span` that just started.

      - parent_context (`Context` | `None`) – The parent context of the span that just started.

    Return type:

      `None`

  on_end(span)

    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()

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

    Return type:

      `None`

  force_flush(timeout_millis=30000)

    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

  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)

    Adds a SpanProcessor to the list handled by this instance.

    Return type:

      `None`

  on_start(span, parent_context=None)

    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:

      - span (`Span`) – The `opentelemetry.trace.Span` that just started.

      - parent_context (`Context` | `None`) – The parent context of the span that just started.

    Return type:

      `None`

  on_end(span)

    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()

    Sequentially shuts down all underlying span processors.

    Return type:

      `None`

  force_flush(timeout_millis=30000)

    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)

  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)

    Adds a SpanProcessor to the list handled by this instance.

    Return type:

      `None`

  on_start(span, parent_context=None)

    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:

      - span (`Span`) – The `opentelemetry.trace.Span` that just started.

      - parent_context (`Context` | `None`) – The parent context of the span that just started.

    Return type:

      `None`

  on_end(span)

    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()

    Shuts down all underlying span processors in parallel.

    Return type:

      `None`

  force_flush(timeout_millis=30000)

    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)

  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)

  Bases: `EventBase`

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

  Parameters:

    - name (`str`) – Name of the event.

    - attributes (`Mapping`[`str`, `str` | `bool` | `int` | `float` | `Sequence`[`str`] | `Sequence`[`bool`] | `Sequence`[`int`] | `Sequence`[`float`]] | `None`) – Attributes of the event.

    - timestamp (`int` | `None`) – Timestamp of the event. If `None` it will filled automatically.

  property attributes: Mapping[str, str | bool | int | float | Sequence[str] | Sequence[bool] | Sequence[int] | Sequence[float]] | None
  property dropped_attributes: int

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)

  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 dropped_links: int
  property name: str
  get_span_context()
  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 links: Sequence[Link]
  property resource: Resource
  property instrumentation_info: InstrumentationInfo | None
  property instrumentation_scope: InstrumentationScope | None
  to_json(indent=4)

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)

  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 (`int` | `None`) – 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 (`int` | `None`) – 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 (`int` | `None`) – 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 (`int` | `None`) – 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 (`int` | `None`) – Maximum number of attributes that can be added to an Event. Default: {_DEFAULT_OTEL_EVENT_ATTRIBUTE_COUNT_LIMIT}

    - max_link_attributes (`int` | `None`) – Maximum number of attributes that can be added to a Link. Default: {_DEFAULT_OTEL_LINK_ATTRIBUTE_COUNT_LIMIT}

    - max_attribute_length (`int` | `None`) – Maximum length an attribute value can have. Values longer than the specified length will be truncated.

    - max_span_attribute_length (`int` | `None`) – 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)

  Bases: `Span`, `ReadableSpan`

  See `opentelemetry.trace.Span`.

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

  Parameters:

    - name (`str`) – The name of the operation this span represents

    - context (`SpanContext`) – The immutable span context

    - parent (`SpanContext` | `None`) – This span’s parent’s `opentelemetry.trace.SpanContext`, or None if this is a root span

    - sampler (`Sampler` | `None`) – The sampler used to create this span

    - trace_config (`None`) – TODO

    - resource (`Resource` | `None`) – Entity producing telemetry

    - attributes (`Mapping`[`str`, `str` | `bool` | `int` | `float` | `Sequence`[`str`] | `Sequence`[`bool`] | `Sequence`[`int`] | `Sequence`[`float`]] | `None`) – The span’s attributes to be exported

    - events (`Sequence`[`Event`] | `None`) – Timestamped events to be exported

    - links (`Sequence`[`Link`]) – Links to other spans to be exported

    - span_processor (`SpanProcessor`) – `SpanProcessor` to invoke when starting and ending this `Span`.

    - limits – `SpanLimits` instance that was passed to the `TracerProvider`

  get_span_context()

    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)

    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)

    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)

    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`

  add_link(context, attributes=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 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:

      `None`

  start(start_time=None, parent_context=None)
    Return type:

      `None`

  end(end_time=None)

    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)

    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()

    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)

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

  record_exception(exception, attributes=None, timestamp=None, escaped=False)

    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)

  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)

    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 (`Context` | `None`) – 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 (`Mapping`[`str`, `str` | `bool` | `int` | `float` | `Sequence`[`str`] | `Sequence`[`bool`] | `Sequence`[`int`] | `Sequence`[`float`]] | `None`) – The span’s attributes.

      - links (`Sequence`[`Link`] | `None`) – Links span to other spans

      - start_time (`int` | `None`) – 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)

    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 (`Context` | `None`) – 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 (`Mapping`[`str`, `str` | `bool` | `int` | `float` | `Sequence`[`str`] | `Sequence`[`bool`] | `Sequence`[`int`] | `Sequence`[`float`]] | `None`) – The span’s attributes.

      - links (`Sequence`[`Link`] | `None`) – Links span to other spans

      - start_time (`int` | `None`) – 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)

  Bases: `TracerProvider`

  See `opentelemetry.trace.TracerProvider`.

  property resource: Resource
  get_tracer(instrumenting_module_name, instrumenting_library_version=None, schema_url=None, attributes=None)

    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 (`str` | `None`) – Optional. The version string of the instrumenting library. Usually this should be the same as `importlib.metadata.version(instrumenting_library_name)`.

      - schema_url (`str` | `None`) – Optional. Specifies the Schema URL of the emitted telemetry.

      - attributes (`Mapping`[`str`, `str` | `bool` | `int` | `float` | `Sequence`[`str`] | `Sequence`[`bool`] | `Sequence`[`int`] | `Sequence`[`float`]] | `None`) – Optional. Specifies the attributes of the emitted telemetry.

    Return type:

      `Tracer`

  add_span_processor(span_processor)

    Registers a new `SpanProcessor` for this `TracerProvider`.

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

    Return type:

      `None`

  shutdown()

    Shut down the span processors added to the tracer provider.

    Return type:

      `None`

  force_flush(timeout_millis=30000)

    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.