From 803f52821f0c716feb7cce930870e47f2ce77fff Mon Sep 17 00:00:00 2001 From: thomasgouveia Date: Mon, 6 Nov 2023 16:04:01 +0100 Subject: [PATCH] feat: add `WithSampler` option (#454) Add a new `WithSampler` method allowing end-users to provide their own implementation of OpenTelemetry sampler directly through the package API. Signed-off-by: thomasgouveia --- CHANGELOG.md | 1 + instrumentation.go | 16 +++++++++++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 833288abe..cd266398a 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. ([#468](https://github.com/open-telemetry/opentelemetry-go-instrumentation/pull/468)). ### Changed diff --git a/instrumentation.go b/instrumentation.go index 212b89292..192899e3b 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,12 @@ 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. +func WithSampler(sampler trace.Sampler) InstrumentationOption { + return fnOpt(func(_ context.Context, c instConfig) (instConfig, error) { + c.sampler = sampler + return c, nil + }) +}