Skip to content

Commit 560fd0a

Browse files
committed
add sampling rate
1 parent ea54fe7 commit 560fd0a

File tree

2 files changed

+13
-7
lines changed

2 files changed

+13
-7
lines changed

main.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ var (
8686
leaderElectionRenewDeadline time.Duration
8787
leaderElectionRetryPeriod time.Duration
8888
enableTracing bool
89+
samplingRate float64
8990
)
9091

9192
func main() {
@@ -150,7 +151,7 @@ func main() {
150151
ctx := ctrl.SetupSignalHandler()
151152

152153
if enableTracing {
153-
if err := ot.RegisterTracing(ctx, setupLog); err != nil {
154+
if err := ot.RegisterTracing(ctx, samplingRate, setupLog); err != nil {
154155
setupLog.Error(err, "unable to set up tracing")
155156
os.Exit(1)
156157
}
@@ -381,5 +382,11 @@ func initFlags(fs *pflag.FlagSet) {
381382
"Enable collecting and sending traces to opentelemetry-collector service",
382383
)
383384

385+
fs.Float64Var(&samplingRate,
386+
"trace-sampling-rate",
387+
0.6,
388+
"The fraction of all the traces will be sample",
389+
)
390+
384391
feature.MutableGates.AddFlag(fs)
385392
}

pkg/otel/tracing.go

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,9 @@ import (
2020
semconv "go.opentelemetry.io/otel/semconv/v1.4.0"
2121
)
2222

23-
func RegisterTracing(ctx context.Context, log logr.Logger) error {
23+
func RegisterTracing(ctx context.Context, samplingRate float64, log logr.Logger) error {
2424

25-
tracerProvider, err := SetUpTracing(ctx)
25+
tracerProvider, err := SetUpTracing(ctx, samplingRate)
2626
if err != nil {
2727
return err
2828
}
@@ -64,7 +64,7 @@ func newExporter(ctx context.Context) (*otlptrace.Exporter, error) {
6464
return traceExporter, nil
6565
}
6666

67-
func SetUpTracing(ctx context.Context) (*trace.TracerProvider, error) {
67+
func SetUpTracing(ctx context.Context, samplingRate float64) (*trace.TracerProvider, error) {
6868

6969
traceExporter, err := newExporter(ctx)
7070

@@ -89,9 +89,8 @@ func SetUpTracing(ctx context.Context) (*trace.TracerProvider, error) {
8989
traceProvider := trace.NewTracerProvider(
9090
trace.WithBatcher(traceExporter),
9191
trace.WithResource(resource),
92-
// TODO: dynamic sampling rate?
93-
// sampling rate based on parent span = 60%
94-
trace.WithSampler(trace.ParentBased(trace.TraceIDRatioBased(0.6))),
92+
// 0 < samplingRate <= 1 (< 0 -> be treated as 0; >= 1 -> always sample)
93+
trace.WithSampler(trace.ParentBased(trace.TraceIDRatioBased(samplingRate))),
9594
)
9695

9796
otel.SetTracerProvider(traceProvider)

0 commit comments

Comments
 (0)