diff --git a/CHANGELOG.md b/CHANGELOG.md index 833288abe..e5bb02264 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ OpenTelemetry Go Automatic Instrumentation adheres to [Semantic Versioning](http - Add the `WithTraceExporter` `InstrumentationOption` to configure the trace `SpanExporter` used by an `Instrumentation`. ([#426](https://github.com/open-telemetry/opentelemetry-go-instrumentation/pull/426)) - Add HTTP status code attribute to `net/http` server instrumentation. ([#428](https://github.com/open-telemetry/opentelemetry-go-instrumentation/pull/428)) - The instrumentation scope now includes the version of the auto-instrumentation project. ([#442](https://github.com/open-telemetry/opentelemetry-go-instrumentation/pull/442)) +- Add a new `WithSampler` method allowing end-users to provide their own implementation of OpenTelemetry sampler directly through the package API. ([#454](https://github.com/open-telemetry/opentelemetry-go-instrumentation/pull/468)). ### Changed diff --git a/instrumentation.go b/instrumentation.go index 212b89292..168538674 100644 --- a/instrumentation.go +++ b/instrumentation.go @@ -163,6 +163,7 @@ type InstrumentationOption interface { } type instConfig struct { + sampler trace.Sampler traceExp trace.SpanExporter target process.TargetArgs serviceName string @@ -192,6 +193,10 @@ func newInstConfig(ctx context.Context, opts []InstrumentationOption) (instConfi err = errors.Join(err, e) } + if c.sampler == nil { + c.sampler = trace.AlwaysSample() + } + return c, err } @@ -216,7 +221,7 @@ func (c instConfig) validate() error { func (c instConfig) tracerProvider() *trace.TracerProvider { return trace.NewTracerProvider( - trace.WithSampler(trace.AlwaysSample()), + trace.WithSampler(c.sampler), trace.WithResource(c.res()), trace.WithBatcher(c.traceExp), trace.WithIDGenerator(opentelemetry.NewEBPFSourceIDGenerator()), @@ -382,3 +387,16 @@ func WithTraceExporter(exp trace.SpanExporter) InstrumentationOption { return c, nil }) } + +// WithSampler returns an [InstrumentationOption] that will configure +// an [Instrumentation] to use the provided sampler to sample OpenTelemetry traces. +// +// If OTEL_TRACES_SAMPLER is defined, this option will conflict with +// [WithEnv]. If both are used, the last one provided to an [Instrumentation] +// will be used. +func WithSampler(sampler trace.Sampler) InstrumentationOption { + return fnOpt(func(_ context.Context, c instConfig) (instConfig, error) { + c.sampler = sampler + return c, nil + }) +}