Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 37 additions & 1 deletion docs/trace/customizing-the-sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,9 @@ If no sampler is explicitly configured, the default is to use
be used to set sampler. Only one sampler can be associated with a provider. If
`SetSampler` is called multiple times, the last one wins. Also, it is not
possible to change the sampler *after* the provider is built, by calling the
`Build()` method on the `TracerProviderBuilder`.
`Build()` method on the `TracerProviderBuilder`. To adjust the sampler the SDK
selected instead of choosing it outright, see
[Adjusting the sampler](#adjusting-the-sampler).

The snippet below shows configuring a custom sampler to the provider.

Expand Down Expand Up @@ -386,6 +388,35 @@ probability configured via the `OTEL_TRACES_SAMPLER_ARG` environment variable.
Follow [this](../extending-the-sdk/README.md#sampler) document
to learn about writing custom samplers.

#### Adjusting the sampler

`SetSampler` sets the sampler unconditionally: any `OTEL_TRACES_SAMPLER` value
is ignored. This is appropriate for an application that fully controls its own
configuration, but causes problems for a library that wants to influence
sampling without affecting any explicit user configuration of the sampler.

`ConfigureSampler` registers a callback which receives the sampler the SDK
resolved - whether that came from `SetSampler`, from `OTEL_TRACES_SAMPLER`, or
from the default - and returns the sampler to use. The callback can return the
sampler it was given, wrap it, or return a different one:

```csharp
using OpenTelemetry;
using OpenTelemetry.Trace;

var tracerProvider = Sdk.CreateTracerProviderBuilder()
.ConfigureSampler((serviceProvider, sampler) => new MySamplerWrapper(sampler))
.Build();
```

The callback runs once, while the provider is being built. Registering it several
times chains the callbacks in registration order, each one receiving the sampler
returned by the previous one, so several libraries can take part without
conflicting. Returning `null` or throwing from a callback fails the build.

When a callback returns a sampler other than the one it was given, the provider
disposes only the final resolved sampler.

#### Troubleshooting: spans dropped due to an unsampled parent

The default sampler is `ParentBased(root=AlwaysOn)`. As the name implies, when a
Expand Down Expand Up @@ -571,6 +602,11 @@ it is shutdown.
implementationFactory)`: Adds a processor into the `TracerProvider` using a
factory function to create the processor instance.

* `ConfigureSampler(Func<IServiceProvider, Sampler, Sampler> configureSampler)`:
Registers a callback function which receives the sampler the SDK resolved and
returns the sampler the `TracerProvider` should use. See
[Adjusting the sampler](#adjusting-the-sampler).

* `ConfigureServices`: Registers a callback function for configuring the
`IServiceCollection` used by the `TracerProviderBuilder`.

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
static OpenTelemetry.Trace.TracerProviderBuilderExtensions.ConfigureSampler(this OpenTelemetry.Trace.TracerProviderBuilder! tracerProviderBuilder, System.Func<System.IServiceProvider!, OpenTelemetry.Trace.Sampler!, OpenTelemetry.Trace.Sampler!>! configureSampler) -> OpenTelemetry.Trace.TracerProviderBuilder!
6 changes: 6 additions & 0 deletions src/OpenTelemetry/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ Notes](../../RELEASENOTES.md).
inherited asynchronous execution contexts.
([#7803](https://github.com/open-telemetry/opentelemetry-dotnet/pull/7803))

* Added `TracerProviderBuilder.ConfigureSampler` which registers a callback
invoked during provider construction with the resolved `Sampler`, allowing the
sampler to be wrapped, conditionally replaced, or observed without discarding
any sampler configured by the `OTEL_TRACES_SAMPLER` environment variable.
([#7780](https://github.com/open-telemetry/opentelemetry-dotnet/pull/7780))

## 1.19.1

Released 2026-Sep-21
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,14 @@ public static TracerProviderBuilder SetErrorStatusOnException(this TracerProvide
/// <summary>
/// Sets sampler.
/// </summary>
/// <remarks>
/// <para sampler-precedence="true">Note: A sampler set programmatically
/// takes precedence over the <c>OTEL_TRACES_SAMPLER</c> environment
/// variable, which in turn takes precedence over the default sampler
/// (<c>ParentBased(AlwaysOnSampler)</c>). To adjust the sampler the SDK
/// resolves, instead of overriding it, use
/// <see cref="ConfigureSampler(TracerProviderBuilder, Func{IServiceProvider, Sampler, Sampler})"/>.</para>
/// </remarks>
/// <param name="tracerProviderBuilder"><see cref="TracerProviderBuilder"/>.</param>
/// <param name="sampler">Sampler instance.</param>
/// <returns>Returns <see cref="TracerProviderBuilder"/> for chaining.</returns>
Expand All @@ -70,8 +78,9 @@ public static TracerProviderBuilder SetSampler(this TracerProviderBuilder tracer
/// Sets the sampler on the provider.
/// </summary>
/// <remarks>
/// Note: The type specified by <typeparamref name="T"/> will be
/// registered as a singleton service into application services.
/// <para>Note: The type specified by <typeparamref name="T"/> will be
/// registered as a singleton application service.</para>
/// <inheritdoc cref="SetSampler(TracerProviderBuilder, Sampler)" path="/remarks/para"/>
/// </remarks>
/// <typeparam name="T">Sampler type.</typeparam>
/// <param name="tracerProviderBuilder"><see cref="TracerProviderBuilder"/>.</param>
Expand Down Expand Up @@ -99,6 +108,7 @@ public static TracerProviderBuilder SetSampler<
/// <summary>
/// Sets the sampler on the provider.
/// </summary>
/// <remarks><inheritdoc cref="SetSampler(TracerProviderBuilder, Sampler)" path="/remarks/para"/></remarks>
/// <param name="tracerProviderBuilder"><see cref="TracerProviderBuilder"/>.</param>
/// <param name="implementationFactory">The factory that creates the service.</param>
/// <returns>The supplied <see cref="TracerProviderBuilder"/> for chaining.</returns>
Expand All @@ -119,6 +129,50 @@ public static TracerProviderBuilder SetSampler(
return tracerProviderBuilder;
}

/// <summary>
/// Registers a callback which receives the <see cref="Sampler"/> resolved
/// by the SDK and returns the <see cref="Sampler"/> the provider should
/// use.
/// </summary>
/// <remarks>
/// <para>Note: Unlike <see cref="SetSampler(TracerProviderBuilder, Sampler)"/>,
/// this method does not discard a sampler configured using the
/// <c>OTEL_TRACES_SAMPLER</c> environment variable.</para>
/// <para>The callback is invoked once, while the
/// <see cref="TracerProvider"/> is being built, and is passed the sampler
/// which would otherwise have been used. The callback may return the original
/// sampler unchanged. Returning <see langword="null"/> or throwing an exception
/// causes building the trace provider to fail.</para>
/// <para>When called multiple times the callbacks are chained in
/// registration order, each receiving the sampler returned by the previous
/// one.</para>
/// <para>The provider only disposes the final resolved sampler. Any sampler
/// which is replaced by a callback is not disposed of by the provider; a callback which
/// discards the sampler it receives, or wraps it, is responsible for that
/// sampler's lifetime.</para>
/// </remarks>
/// <param name="tracerProviderBuilder"><see cref="TracerProviderBuilder"/>.</param>
/// <param name="configureSampler">Callback which receives the resolved
/// <see cref="Sampler"/> and returns the <see cref="Sampler"/> to use.</param>
/// <returns>The supplied <see cref="TracerProviderBuilder"/> for chaining.</returns>
/// <exception cref="ArgumentNullException"><paramref name="configureSampler"/> is <see langword="null"/>.</exception>
public static TracerProviderBuilder ConfigureSampler(
this TracerProviderBuilder tracerProviderBuilder,
Func<IServiceProvider, Sampler, Sampler> configureSampler)
{
Guard.ThrowIfNull(configureSampler);

tracerProviderBuilder.ConfigureBuilder((sp, builder) =>
{
if (builder is TracerProviderBuilderSdk tracerProviderBuilderSdk)
{
tracerProviderBuilderSdk.AddSamplerConfigurator(configureSampler);
}
});

return tracerProviderBuilder;
}

/// <summary>
/// Sets the <see cref="ResourceBuilder"/> from which the Resource associated with
/// this provider is built from. Overwrites currently set ResourceBuilder.
Expand Down
13 changes: 13 additions & 0 deletions src/OpenTelemetry/Trace/Builder/TracerProviderBuilderSdk.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ internal sealed class TracerProviderBuilderSdk : TracerProviderBuilder, ITracerP

private readonly IServiceProvider serviceProvider;
private TracerProviderSdk? tracerProvider;
private List<Func<IServiceProvider, Sampler, Sampler>>? samplerConfigurators;

public TracerProviderBuilderSdk(IServiceProvider serviceProvider)
{
Expand All @@ -37,6 +38,9 @@ public TracerProviderBuilderSdk(IServiceProvider serviceProvider)

public Sampler? Sampler { get; private set; }

public IReadOnlyList<Func<IServiceProvider, Sampler, Sampler>> SamplerConfigurators
=> this.samplerConfigurators ?? [];

public bool ExceptionProcessorEnabled { get; private set; }

public void RegisterProvider(TracerProviderSdk tracerProvider)
Expand Down Expand Up @@ -127,6 +131,15 @@ public TracerProviderBuilder SetSampler(Sampler sampler)
return this;
}

public TracerProviderBuilder AddSamplerConfigurator(Func<IServiceProvider, Sampler, Sampler> configurator)
{
Debug.Assert(configurator != null, "configurator was null");

(this.samplerConfigurators ??= []).Add(configurator!);

return this;
}

public TracerProviderBuilder SetErrorStatusOnException(bool enabled)
{
this.ExceptionProcessorEnabled = enabled;
Expand Down
22 changes: 22 additions & 0 deletions src/OpenTelemetry/Trace/TracerProviderSdk.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,28 @@ internal TracerProviderSdk(
this.Sampler = GetSampler(serviceProvider!.GetRequiredService<IConfiguration>(), state.Sampler);
OpenTelemetrySdkEventSource.Log.TracerProviderSdkEvent($"Sampler added = \"{this.Sampler.GetType()}\".");

// this.Sampler is assigned on each iteration so a sampler returned by any
// callback remains reachable by DisposeBuiltState if a later callback fails.
var samplerConfigurators = state.SamplerConfigurators;
for (var i = 0; i < samplerConfigurators.Count; i++)
{
var currentSampler = this.Sampler;
var configuredSampler = samplerConfigurators[i](serviceProvider!, currentSampler)
?? throw new InvalidOperationException($"A callback registered using '{nameof(TracerProviderBuilderExtensions.ConfigureSampler)}' returned null. The callback must return a Sampler instance.");

if (!ReferenceEquals(configuredSampler, currentSampler))
{
this.Sampler = configuredSampler;
OpenTelemetrySdkEventSource.Log.TracerProviderSdkEvent(
$"Sampler configurator {i + 1} of {samplerConfigurators.Count} changed sampler from \"{currentSampler.GetType()}\" to \"{configuredSampler.GetType()}\".");
}
else
{
OpenTelemetrySdkEventSource.Log.TracerProviderSdkEvent(
$"Sampler configurator {i + 1} of {samplerConfigurators.Count} left sampler \"{currentSampler.GetType()}\" unchanged.");
}
}

this.supportLegacyActivity = state.LegacyActivityOperationNames.Count > 0;

Regex? legacyActivityWildcardModeRegex = null;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using OpenTelemetry.Trace;

namespace OpenTelemetry.Tests;

internal static class SamplerConfigurationTestHelper
{
/// <summary>
/// Supplies <c>OTEL_TRACES_SAMPLER</c> and <c>OTEL_TRACES_SAMPLER_ARG</c> to
/// <paramref name="builder"/> using an in-memory <see cref="IConfiguration"/>.
/// </summary>
/// <param name="builder"><see cref="TracerProviderBuilder"/>.</param>
/// <param name="samplerConfigValue">Value for <c>OTEL_TRACES_SAMPLER</c>.</param>
/// <param name="samplerArgConfigValue">Value for <c>OTEL_TRACES_SAMPLER_ARG</c>.</param>
/// <returns>The supplied <see cref="TracerProviderBuilder"/> for chaining.</returns>
public static TracerProviderBuilder AddSamplerConfiguration(
this TracerProviderBuilder builder,
string? samplerConfigValue,
string? samplerArgConfigValue = null)
{
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?>
{
[TracerProviderSdk.TracesSamplerConfigKey] = samplerConfigValue,
[TracerProviderSdk.TracesSamplerArgConfigKey] = samplerArgConfigValue,
})
.Build();

return builder.ConfigureServices(services => services.AddSingleton<IConfiguration>(configuration));
}
}
Loading
Loading