5
5
"fmt"
6
6
"strings"
7
7
"sync"
8
+ "sync/atomic"
8
9
"time"
9
10
10
11
"go.opentelemetry.io/otel/attribute"
@@ -122,19 +123,28 @@ func (_this *otelMetricService) RecordGauge(ctx context.Context, name string, va
122
123
gaugeKey := fmt .Sprintf ("%s_%s" , config .ServiceName , name )
123
124
124
125
gaugeInterface , _ := _this .gauges .LoadOrStore (gaugeKey , & struct {
125
- gauge metric.Float64UpDownCounter
126
+ gauge metric.Float64ObservableGauge
127
+ value atomic.Value
126
128
once sync.Once
127
129
}{})
128
130
129
131
gaugeData := gaugeInterface .(* struct {
130
- gauge metric.Float64UpDownCounter
132
+ gauge metric.Float64ObservableGauge
133
+ value atomic.Value
131
134
once sync.Once
132
135
})
133
136
134
137
gaugeData .once .Do (func () {
135
- gauge , err := _this .meter .Float64UpDownCounter (
138
+ gauge , err := _this .meter .Float64ObservableGauge (
136
139
gaugeKey ,
137
140
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
+ }),
138
148
)
139
149
if err != nil {
140
150
_this .logger .Errorw ("failed to create gauge" , "error" , err )
@@ -143,22 +153,7 @@ func (_this *otelMetricService) RecordGauge(ctx context.Context, name string, va
143
153
gaugeData .gauge = gauge
144
154
})
145
155
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 )
156
158
return nil
157
159
}
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