Skip to content

Commit 32b80d9

Browse files
committed
fix: use observable gauge instead of up-down counter
1 parent f93c713 commit 32b80d9

File tree

1 file changed

+15
-20
lines changed

1 file changed

+15
-20
lines changed

common/metric/otel.go

+15-20
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"fmt"
66
"strings"
77
"sync"
8+
"sync/atomic"
89
"time"
910

1011
"go.opentelemetry.io/otel/attribute"
@@ -122,19 +123,28 @@ func (_this *otelMetricService) RecordGauge(ctx context.Context, name string, va
122123
gaugeKey := fmt.Sprintf("%s_%s", config.ServiceName, name)
123124

124125
gaugeInterface, _ := _this.gauges.LoadOrStore(gaugeKey, &struct {
125-
gauge metric.Float64UpDownCounter
126+
gauge metric.Float64ObservableGauge
127+
value atomic.Value
126128
once sync.Once
127129
}{})
128130

129131
gaugeData := gaugeInterface.(*struct {
130-
gauge metric.Float64UpDownCounter
132+
gauge metric.Float64ObservableGauge
133+
value atomic.Value
131134
once sync.Once
132135
})
133136

134137
gaugeData.once.Do(func() {
135-
gauge, err := _this.meter.Float64UpDownCounter(
138+
gauge, err := _this.meter.Float64ObservableGauge(
136139
gaugeKey,
137140
metric.WithDescription("Gauge measurement"),
141+
metric.WithFloat64Callback(func(_ context.Context, o metric.Float64Observer) error {
142+
val := gaugeData.value.Load()
143+
if val != nil {
144+
o.Observe(val.(float64), metric.WithAttributes(attrs...))
145+
}
146+
return nil
147+
}),
138148
)
139149
if err != nil {
140150
_this.logger.Errorw("failed to create gauge", "error", err)
@@ -143,22 +153,7 @@ func (_this *otelMetricService) RecordGauge(ctx context.Context, name string, va
143153
gaugeData.gauge = gauge
144154
})
145155

146-
if gaugeData.gauge != nil {
147-
// Calculate the difference from the previous value to the new value
148-
previousValue := _this.getCurrentValue(gaugeKey)
149-
diff := value - previousValue
150-
gaugeData.gauge.Add(ctx, diff, metric.WithAttributes(attrs...))
151-
152-
// Store the new value
153-
_this.gauges.Store(gaugeKey+"_value", value)
154-
}
155-
156+
// Store the new value directly
157+
gaugeData.value.Store(value)
156158
return nil
157159
}
158-
159-
func (_this *otelMetricService) getCurrentValue(key string) float64 {
160-
if val, exists := _this.gauges.Load(key + "_value"); exists {
161-
return val.(float64)
162-
}
163-
return 0
164-
}

0 commit comments

Comments
 (0)