# opentelemetry.sdk.trace.sampling

For general information about sampling, see the specification.

OpenTelemetry provides two types of samplers:

- `StaticSampler`

- `TraceIdRatioBased`

A `StaticSampler` always returns the same sampling result regardless of the conditions. Both possible StaticSamplers are already created:

- Always sample spans: ALWAYS_ON

- Never sample spans: ALWAYS_OFF

A `TraceIdRatioBased` sampler makes a random sampling result based on the sampling probability given.

If the span being sampled has a parent, `ParentBased` will respect the parent delegate sampler. Otherwise, it returns the sampling result from the given root sampler.

Currently, sampling results are always made during the creation of the span. However, this might not always be the case in the future (see OTEP #115).

Custom samplers can be created by subclassing `Sampler` and implementing `Sampler.should_sample` as well as `Sampler.get_description`.

Samplers are able to modify the `opentelemetry.trace.span.TraceState` of the parent of the span being created. For custom samplers, it is suggested to implement `Sampler.should_sample` to utilize the parent span context’s `opentelemetry.trace.span.TraceState` and pass into the `SamplingResult` instead of the explicit trace_state field passed into the parameter of `Sampler.should_sample`.

To use a sampler, pass it into the tracer provider constructor. For example:

    from opentelemetry import trace
    from opentelemetry.sdk.trace import TracerProvider
    from opentelemetry.sdk.trace.export import (
        ConsoleSpanExporter,
        SimpleSpanProcessor,
    )
    from opentelemetry.sdk.trace.sampling import TraceIdRatioBased

    # sample 1 in every 1000 traces
    sampler = TraceIdRatioBased(1/1000)

    # set the sampler onto the global tracer provider
    trace.set_tracer_provider(TracerProvider(sampler=sampler))

    # set up an exporter for sampled spans
    trace.get_tracer_provider().add_span_processor(
        SimpleSpanProcessor(ConsoleSpanExporter())
    )

    # created spans will now be sampled by the TraceIdRatioBased sampler
    with trace.get_tracer(__name__).start_as_current_span("Test Span"):
        ...

The tracer sampler can also be configured via environment variables `OTEL_TRACES_SAMPLER` and `OTEL_TRACES_SAMPLER_ARG` (only if applicable). The list of built-in values for `OTEL_TRACES_SAMPLER` are:

> - always_on - Sampler that always samples spans, regardless of the parent span’s sampling decision.

> - always_off - Sampler that never samples spans, regardless of the parent span’s sampling decision.

> - traceidratio - Sampler that samples probabilistically based on rate.

> - parentbased_always_on - (default) Sampler that respects its parent span’s sampling decision, but otherwise always samples.

> - parentbased_always_off - Sampler that respects its parent span’s sampling decision, but otherwise never samples.

> - parentbased_traceidratio - Sampler that respects its parent span’s sampling decision, but otherwise samples probabilistically based on rate.

Sampling probability can be set with `OTEL_TRACES_SAMPLER_ARG` if the sampler is traceidratio or parentbased_traceidratio. Rate must be in the range [0.0,1.0]. When not provided rate will be set to 1.0 (maximum rate possible).

Prev example but with environment variables. Please make sure to set the env `OTEL_TRACES_SAMPLER=traceidratio` and `OTEL_TRACES_SAMPLER_ARG=0.001`.

    from opentelemetry import trace
    from opentelemetry.sdk.trace import TracerProvider
    from opentelemetry.sdk.trace.export import (
        ConsoleSpanExporter,
        SimpleSpanProcessor,
    )

    trace.set_tracer_provider(TracerProvider())

    # set up an exporter for sampled spans
    trace.get_tracer_provider().add_span_processor(
        SimpleSpanProcessor(ConsoleSpanExporter())
    )

    # created spans will now be sampled by the TraceIdRatioBased sampler with rate 1/1000.
    with trace.get_tracer(__name__).start_as_current_span("Test Span"):
        ...

When utilizing a configurator, you can configure a custom sampler. In order to create a configurable custom sampler, create an entry point for the custom sampler factory method or function under the entry point group, `opentelemetry_traces_sampler`. The custom sampler factory method must be of type `Callable[[str], Sampler]`, taking a single string argument and returning a Sampler object. The single input will come from the string value of the `OTEL_TRACES_SAMPLER_ARG` environment variable. If `OTEL_TRACES_SAMPLER_ARG` is not configured, the input will be an empty string. For example:

    setup(
        ...
        entry_points={
            ...
            "opentelemetry_traces_sampler": [
                "custom_sampler_name = path.to.sampler.factory.method:CustomSamplerFactory.get_sampler"
            ]
        }
    )
    # ...
    class CustomRatioSampler(Sampler):
        def __init__(rate):
            # ...
    # ...
    class CustomSamplerFactory:
        @staticmethod
        def get_sampler(sampler_argument):
            try:
                rate = float(sampler_argument)
                return CustomSampler(rate)
            except ValueError: # In case argument is empty string.
                return CustomSampler(0.5)

In order to configure you application with a custom sampler’s entry point, set the `OTEL_TRACES_SAMPLER` environment variable to the key name of the entry point. For example, to configured the above sampler, set `OTEL_TRACES_SAMPLER=custom_sampler_name` and `OTEL_TRACES_SAMPLER_ARG=0.5`.

class opentelemetry.sdk.trace.sampling.Decision(*values)

  Bases: `Enum`

  DROP = 0
  RECORD_ONLY = 1
  RECORD_AND_SAMPLE = 2
  is_recording()
  is_sampled()

class opentelemetry.sdk.trace.sampling.SamplingResult(decision, attributes=None, trace_state=None)

  Bases: `object`

  A sampling result as applied to a newly-created Span.

  Parameters:

    - decision (`Decision`) – A sampling decision based off of whether the span is recorded and the sampled flag in trace flags in the span context.

    - attributes (`Mapping`[`str`, `str` | `bool` | `int` | `float` | `Sequence`[`str`] | `Sequence`[`bool`] | `Sequence`[`int`] | `Sequence`[`float`]] | `None`) – Attributes to add to the `opentelemetry.trace.Span`.

    - trace_state (`TraceState` | `None`) – The tracestate used for the `opentelemetry.trace.Span`. Could possibly have been modified by the sampler.

class opentelemetry.sdk.trace.sampling.Sampler

  Bases: `ABC`

  abstractmethod should_sample(parent_context, trace_id, name, kind=None, attributes=None, links=None, trace_state=None)
    Return type:

      `SamplingResult`

  abstractmethod get_description()
    Return type:

      `str`

class opentelemetry.sdk.trace.sampling.StaticSampler(decision)

  Bases: `Sampler`

  Sampler that always returns the same decision.

  should_sample(parent_context, trace_id, name, kind=None, attributes=None, links=None, trace_state=None)
    Return type:

      `SamplingResult`

  get_description()
    Return type:

      `str`

opentelemetry.sdk.trace.sampling.ALWAYS_OFF = <opentelemetry.sdk.trace.sampling.StaticSampler object>

  Sampler that never samples spans, regardless of the parent span’s sampling decision.

opentelemetry.sdk.trace.sampling.ALWAYS_ON = <opentelemetry.sdk.trace.sampling.StaticSampler object>

  Sampler that always samples spans, regardless of the parent span’s sampling decision.

class opentelemetry.sdk.trace.sampling.TraceIdRatioBased(rate)

  Bases: `Sampler`

  Sampler that makes sampling decisions probabilistically based on `rate`.

  Parameters:

    rate (`float`) – Probability (between 0 and 1) that a span will be sampled

  TRACE_ID_LIMIT = 18446744073709551615
  classmethod get_bound_for_rate(rate)
    Return type:

      `int`

  property rate: float
  property bound: int
  should_sample(parent_context, trace_id, name, kind=None, attributes=None, links=None, trace_state=None)
    Return type:

      `SamplingResult`

  get_description()
    Return type:

      `str`

class opentelemetry.sdk.trace.sampling.ParentBased(root, remote_parent_sampled=<opentelemetry.sdk.trace.sampling.StaticSampler object>, remote_parent_not_sampled=<opentelemetry.sdk.trace.sampling.StaticSampler object>, local_parent_sampled=<opentelemetry.sdk.trace.sampling.StaticSampler object>, local_parent_not_sampled=<opentelemetry.sdk.trace.sampling.StaticSampler object>)

  Bases: `Sampler`

  If a parent is set, applies the respective delegate sampler. Otherwise, uses the root provided at initialization to make a decision.

  Parameters:

    - root (`Sampler`) – Sampler called for spans with no parent (root spans).

    - remote_parent_sampled (`Sampler`) – Sampler called for a remote sampled parent.

    - remote_parent_not_sampled (`Sampler`) – Sampler called for a remote parent that is not sampled.

    - local_parent_sampled (`Sampler`) – Sampler called for a local sampled parent.

    - local_parent_not_sampled (`Sampler`) – Sampler called for a local parent that is not sampled.

  should_sample(parent_context, trace_id, name, kind=None, attributes=None, links=None, trace_state=None)
    Return type:

      `SamplingResult`

  get_description()

opentelemetry.sdk.trace.sampling.DEFAULT_OFF = <opentelemetry.sdk.trace.sampling.ParentBased object>

  Sampler that respects its parent span’s sampling decision, but otherwise never samples.

opentelemetry.sdk.trace.sampling.DEFAULT_ON = <opentelemetry.sdk.trace.sampling.ParentBased object>

  Sampler that respects its parent span’s sampling decision, but otherwise always samples.

class opentelemetry.sdk.trace.sampling.ParentBasedTraceIdRatio(rate)

  Bases: `ParentBased`

  Sampler that respects its parent span’s sampling decision, but otherwise samples probabilistically based on `rate`.