1 // Copyright 2017, OpenCensus Authors
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
21 const defaultSamplingProbability = 1e-4
23 // Sampler decides whether a trace should be sampled and exported.
24 type Sampler func(SamplingParameters) SamplingDecision
26 // SamplingParameters contains the values passed to a Sampler.
27 type SamplingParameters struct {
28 ParentContext SpanContext
35 // SamplingDecision is the value returned by a Sampler.
36 type SamplingDecision struct {
40 // ProbabilitySampler returns a Sampler that samples a given fraction of traces.
42 // It also samples spans whose parents are sampled.
43 func ProbabilitySampler(fraction float64) Sampler {
46 } else if fraction >= 1 {
50 traceIDUpperBound := uint64(fraction * (1 << 63))
51 return Sampler(func(p SamplingParameters) SamplingDecision {
52 if p.ParentContext.IsSampled() {
53 return SamplingDecision{Sample: true}
55 x := binary.BigEndian.Uint64(p.TraceID[0:8]) >> 1
56 return SamplingDecision{Sample: x < traceIDUpperBound}
60 // AlwaysSample returns a Sampler that samples every trace.
61 // Be careful about using this sampler in a production application with
62 // significant traffic: a new trace will be started and exported for every
64 func AlwaysSample() Sampler {
65 return func(p SamplingParameters) SamplingDecision {
66 return SamplingDecision{Sample: true}
70 // NeverSample returns a Sampler that samples no traces.
71 func NeverSample() Sampler {
72 return func(p SamplingParameters) SamplingDecision {
73 return SamplingDecision{Sample: false}