Skip to content

Commit

Permalink
Merge pull request #370 from ww24/add-otel-custom-sampler
Browse files Browse the repository at this point in the history
fix(trace): add custom sampler
  • Loading branch information
ww24 authored Oct 22, 2022
2 parents 8f76da5 + a5eae78 commit 88fd5a0
Showing 1 changed file with 35 additions and 5 deletions.
40 changes: 35 additions & 5 deletions tracer/tracer.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package tracer

import (
"context"
"strings"
"time"

cloudtrace "github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/trace"
Expand Down Expand Up @@ -41,11 +42,13 @@ func New(c *Config, conf repository.Config, exporter sdktrace.SpanExporter) (tra
semconv.ServiceVersionKey.String(c.version),
)

sampler := sdktrace.ParentBased(sdktrace.TraceIDRatioBased(conf.OTELSamplingRate()),
sdktrace.WithLocalParentSampled(sdktrace.AlwaysSample()),
sdktrace.WithLocalParentNotSampled(sdktrace.NeverSample()),
sdktrace.WithRemoteParentSampled(sdktrace.AlwaysSample()),
sdktrace.WithRemoteParentNotSampled(sdktrace.NeverSample()),
sampler := newCustomSampler(
sdktrace.ParentBased(sdktrace.TraceIDRatioBased(conf.OTELSamplingRate()),
sdktrace.WithLocalParentSampled(sdktrace.AlwaysSample()),
sdktrace.WithLocalParentNotSampled(sdktrace.NeverSample()),
sdktrace.WithRemoteParentSampled(sdktrace.AlwaysSample()),
sdktrace.WithRemoteParentNotSampled(sdktrace.NeverSample()),
),
)

tp := sdktrace.NewTracerProvider(
Expand Down Expand Up @@ -84,3 +87,30 @@ func NewCloudTraceExporter() (sdktrace.SpanExporter, error) {
}
return exporter, nil
}

// customSampler implements sdktrace.Sampler.
var _ sdktrace.Sampler = (*customSampler)(nil)

type customSampler struct {
parent sdktrace.Sampler
}

func newCustomSampler(parent sdktrace.Sampler) *customSampler {
return &customSampler{parent: parent}
}

//nolint:gocritic
func (s *customSampler) ShouldSample(p sdktrace.SamplingParameters) sdktrace.SamplingResult {
if strings.HasPrefix(p.Name, "google.devtools.cloudtrace.") ||
strings.HasPrefix(p.Name, "google.devtools.cloudprofiler.") {
return sdktrace.SamplingResult{
Decision: sdktrace.Drop,
Tracestate: trace.SpanContextFromContext(p.ParentContext).TraceState(),
}
}
return s.parent.ShouldSample(p)
}

func (s *customSampler) Description() string {
return "CustomSampler"
}

0 comments on commit 88fd5a0

Please sign in to comment.