Skip to content

Instantly share code, notes, and snippets.

@ngauthier
Created May 31, 2019 13:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ngauthier/cc6fe542273a6602ef2f37484cf54041 to your computer and use it in GitHub Desktop.
Save ngauthier/cc6fe542273a6602ef2f37484cf54041 to your computer and use it in GitHub Desktop.
package fieldsampler
import (
"github.com/honeycombio/beeline-go/sample"
)
const (
// CustomSampleRateFieldName is the field to use to override the default Sample Rate
CustomSampleRateFieldName = "CustomSampleRate"
// DeterministicSampleFieldName is the field used as a determinant for the sampler
DeterministicSampleFieldName = "trace.trace_id"
)
// NewFieldSamplerHook creates a new SamplerHook that respects CustomSampleRateFieldName if present,
// otherwise it uses the given defaultSampleRate. Then it delegates to the beeline deterministic sampler.
func NewFieldSamplerHook(defaultSampleRate uint) (func(map[string]interface{}) (bool, int), error) {
defaultSampler, err := sample.NewDeterministicSampler(defaultSampleRate)
if err != nil {
return nil, err
}
return func(fields map[string]interface{}) (bool, int) {
sampler := defaultSampler
rate := int(defaultSampleRate)
if custom, ok := fields[CustomSampleRateFieldName].(int); ok {
rate = custom
newSampler, err := sample.NewDeterministicSampler(uint(rate))
if err == nil && rate > 0 {
sampler = newSampler
}
}
determinant := ""
if traceID, ok := fields[DeterministicSampleFieldName].(string); ok {
determinant = traceID
}
shouldSample := sampler.Sample(determinant)
return shouldSample, rate
}, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment