github.com/rudderlabs/rudder-go-kit@v0.30.0/stats/otel_measurement.go (about) 1 package stats 2 3 import ( 4 "context" 5 "sync/atomic" 6 "time" 7 8 "go.opentelemetry.io/otel/attribute" 9 "go.opentelemetry.io/otel/metric" 10 ) 11 12 // otelMeasurement is the statsd-specific implementation of Measurement 13 type otelMeasurement struct { 14 genericMeasurement 15 disabled bool 16 attributes []attribute.KeyValue 17 } 18 19 // otelCounter represents a counter stat 20 type otelCounter struct { 21 *otelMeasurement 22 counter metric.Int64Counter 23 } 24 25 func (c *otelCounter) Count(n int) { 26 if !c.disabled { 27 c.counter.Add(context.TODO(), int64(n), metric.WithAttributes(c.attributes...)) 28 } 29 } 30 31 // Increment increases the stat by 1. Is the Equivalent of Count(1). Only applies to CountType stats 32 func (c *otelCounter) Increment() { 33 if !c.disabled { 34 c.counter.Add(context.TODO(), 1, metric.WithAttributes(c.attributes...)) 35 } 36 } 37 38 // otelGauge represents a gauge stat 39 type otelGauge struct { 40 *otelMeasurement 41 value atomic.Value 42 } 43 44 // Gauge records an absolute value for this stat. Only applies to GaugeType stats 45 func (g *otelGauge) Gauge(value interface{}) { 46 if g.disabled { 47 return 48 } 49 g.value.Store(value) 50 } 51 52 func (g *otelGauge) getValue() interface{} { 53 if g.disabled { 54 return nil 55 } 56 return g.value.Load() 57 } 58 59 // otelTimer represents a timer stat 60 type otelTimer struct { 61 *otelMeasurement 62 now func() time.Time 63 timer metric.Float64Histogram 64 } 65 66 // Since sends the time elapsed since duration start. Only applies to TimerType stats 67 func (t *otelTimer) Since(start time.Time) { 68 if !t.disabled { 69 t.SendTiming(time.Since(start)) 70 } 71 } 72 73 // SendTiming sends a timing for this stat. Only applies to TimerType stats 74 func (t *otelTimer) SendTiming(duration time.Duration) { 75 if !t.disabled { 76 t.timer.Record(context.TODO(), duration.Seconds(), metric.WithAttributes(t.attributes...)) 77 } 78 } 79 80 // RecordDuration records the duration of time between 81 // the call to this function and the execution of the function it returns. 82 // Only applies to TimerType stats 83 func (t *otelTimer) RecordDuration() func() { 84 if t.disabled { 85 return func() {} 86 } 87 var start time.Time 88 if t.now == nil { 89 start = time.Now() 90 } else { 91 start = t.now() 92 } 93 return func() { 94 t.Since(start) 95 } 96 } 97 98 // otelHistogram represents a histogram stat 99 type otelHistogram struct { 100 *otelMeasurement 101 histogram metric.Float64Histogram 102 } 103 104 // Observe sends an observation 105 func (h *otelHistogram) Observe(value float64) { 106 if !h.disabled { 107 h.histogram.Record(context.TODO(), value, metric.WithAttributes(h.attributes...)) 108 } 109 }