Debian Codegraph @

metric/example_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package metric_test
5
6 import (
7 "context"
8 "database/sql"
9 "fmt"
10 "math/rand/v2"
11 "net/http"
12 "runtime"
13 "time"
14
15 "go.opentelemetry.io/otel"
16 "go.opentelemetry.io/otel/attribute"
17 "go.opentelemetry.io/otel/metric"
18 semconv "go.opentelemetry.io/otel/semconv/v1.40.0"
19 )
20
21 var meter = otel.Meter("my-service-meter")
22
23 func ExampleMeter_synchronous() {
24 // Create a histogram using the global MeterProvider.
25 workDuration, err := meter.Int64Histogram(
26 "workDuration",
27 metric.WithUnit("ms"))
28 if err != nil {
29 fmt.Println("Failed to register instrument")
30 panic(err)
31 }
32
33 startTime := time.Now()
34 ctx := context.Background()
35 // Do work
36 // ...
37 workDuration.Record(ctx, time.Since(startTime).Milliseconds())
38 }
39
40 func ExampleMeter_asynchronous_single() {
41 _, err := meter.Int64ObservableGauge(
42 "DiskUsage",
43 metric.WithUnit("By"),
44 metric.WithInt64Callback(func(_ context.Context, obsrv metric.Int64Observer) error {
45 // Do the real work here to get the real disk usage. For example,
46 //
47 // usage, err := GetDiskUsage(diskID)
48 // if err != nil {
49 // if retryable(err) {
50 // // Retry the usage measurement.
51 // } else {
52 // return err
53 // }
54 // }
55 //
56 // For demonstration purpose, a static value is used here.
57 usage := 75000
58 obsrv.Observe(int64(usage), metric.WithAttributes(attribute.Int("disk.id", 3)))
59 return nil
60 }),
61 )
62 if err != nil {
63 fmt.Println("failed to register instrument")
64 panic(err)
65 }
66 }
67
68 func ExampleMeter_asynchronous_multiple() {
69 // This is just a sample of memory stats to record from the Memstats
70 heapAlloc, err := meter.Int64ObservableUpDownCounter("heapAllocs")
71 if err != nil {
72 fmt.Println("failed to register updown counter for heapAllocs")
73 panic(err)
74 }
75 gcCount, err := meter.Int64ObservableCounter("gcCount")
76 if err != nil {
77 fmt.Println("failed to register counter for gcCount")
78 panic(err)
79 }
80
81 _, err = meter.RegisterCallback(
82 func(_ context.Context, o metric.Observer) error {
83 memStats := &runtime.MemStats{}
84 // This call does work
85 runtime.ReadMemStats(memStats)
86
87 o.ObserveInt64(heapAlloc, int64(memStats.HeapAlloc))
88 o.ObserveInt64(gcCount, int64(memStats.NumGC))
89
90 return nil
91 },
92 heapAlloc,
93 gcCount,
94 )
95 if err != nil {
96 fmt.Println("Failed to register callback")
97 panic(err)
98 }
99 }
100
101 // Counters can be used to measure a non-negative, increasing value.
102 //
103 // Here's how you might report the number of calls for an HTTP handler.
104 func ExampleMeter_counter() {
105 apiCounter, err := meter.Int64Counter(
106 "api.counter",
107 metric.WithDescription("Number of API calls."),
108 metric.WithUnit("{call}"),
109 )
110 if err != nil {
111 panic(err)
112 }
113 http.HandleFunc("/", func(_ http.ResponseWriter, r *http.Request) {
114 apiCounter.Add(r.Context(), 1)
115
116 // do some work in an API call
117 })
118 }
119
120 // UpDown counters can increment and decrement, allowing you to observe
121 // a cumulative value that goes up or down.
122 //
123 // Here's how you might report the number of items of some collection.
124 func ExampleMeter_upDownCounter() {
125 var err error
126 itemsCounter, err := meter.Int64UpDownCounter(
127 "items.counter",
128 metric.WithDescription("Number of items."),
129 metric.WithUnit("{item}"),
130 )
131 if err != nil {
132 panic(err)
133 }
134
135 // Add an item to the collection.
136 itemsCounter.Add(context.Background(), 1)
137
138 // Remove an item from the collection.
139 itemsCounter.Add(context.Background(), -1)
140 }
141
142 // Gauges can be used to record non-additive values when changes occur.
143 //
144 // Here's how you might report the current speed of a cpu fan.
145 func ExampleMeter_gauge() {
146 speedGauge, err := meter.Int64Gauge(
147 "cpu.fan.speed",
148 metric.WithDescription("Speed of CPU fan"),
149 metric.WithUnit("RPM"),
150 )
151 if err != nil {
152 panic(err)
153 }
154
155 getCPUFanSpeed := func() int64 {
156 // Generates a random fan speed for demonstration purpose.
157 // In real world applications, replace this to get the actual fan speed.
158 return int64(1500 + rand.IntN(1000))
159 }
160
161 fanSpeedSubscription := make(chan int64, 1)
162 go func() {
163 defer close(fanSpeedSubscription)
164
165 for range 5 {
166 // Synchronous gauges are used when the measurement cycle is
167 // synchronous to an external change.
168 // Simulate that external cycle here.
169 time.Sleep(time.Duration(rand.IntN(3)) * time.Second)
170 fanSpeed := getCPUFanSpeed()
171 fanSpeedSubscription <- fanSpeed
172 }
173 }()
174
175 ctx := context.Background()
176 for fanSpeed := range fanSpeedSubscription {
177 speedGauge.Record(ctx, fanSpeed)
178 }
179 }
180
181 // Histograms are used to measure a distribution of values over time.
182 //
183 // Here's how you might report a distribution of response times for an HTTP handler.
184 func ExampleMeter_histogram() {
185 histogram, err := meter.Float64Histogram(
186 "task.duration",
187 metric.WithDescription("The duration of task execution."),
188 metric.WithUnit("s"),
189 metric.WithExplicitBucketBoundaries(.005, .01, .025, .05, .075, .1, .25, .5, .75, 1, 2.5, 5, 7.5, 10),
190 )
191 if err != nil {
192 panic(err)
193 }
194 http.HandleFunc("/", func(_ http.ResponseWriter, r *http.Request) {
195 start := time.Now()
196
197 // do some work in an API call
198
199 duration := time.Since(start)
200 histogram.Record(r.Context(), duration.Seconds())
201 })
202 }
203
204 // Observable counters can be used to measure an additive, non-negative,
205 // monotonically increasing value.
206 //
207 // Here's how you might report time since the application started.
208 func ExampleMeter_observableCounter() {
209 start := time.Now()
210 if _, err := meter.Float64ObservableCounter(
211 "uptime",
212 metric.WithDescription("The duration since the application started."),
213 metric.WithUnit("s"),
214 metric.WithFloat64Callback(func(_ context.Context, o metric.Float64Observer) error {
215 o.Observe(float64(time.Since(start).Seconds()))
216 return nil
217 }),
218 ); err != nil {
219 panic(err)
220 }
221 }
222
223 // Observable UpDown counters can increment and decrement, allowing you to measure
224 // an additive, non-negative, non-monotonically increasing cumulative value.
225 //
226 // Here's how you might report some database metrics.
227 func ExampleMeter_observableUpDownCounter() {
228 m, err := meter.Int64ObservableUpDownCounter(
229 "db.client.connections.max",
230 metric.WithDescription("The maximum number of open connections allowed."),
231 metric.WithUnit("{connection}"),
232 )
233 if err != nil {
234 panic(err)
235 }
236
237 waitTime, err := meter.Int64ObservableUpDownCounter(
238 "db.client.connections.wait_time",
239 metric.WithDescription("The time it took to obtain an open connection from the pool."),
240 metric.WithUnit("ms"),
241 )
242 if err != nil {
243 panic(err)
244 }
245
246 var db *sql.DB // DB is initialized elsewhere.
247 _, err = meter.RegisterCallback(
248 func(_ context.Context, o metric.Observer) error {
249 stats := db.Stats()
250 o.ObserveInt64(m, int64(stats.MaxOpenConnections))
251 o.ObserveInt64(waitTime, int64(stats.WaitDuration))
252 return nil
253 },
254 m,
255 waitTime,
256 )
257 if err != nil {
258 panic(err)
259 }
260 }
261
262 // Observable Gauges should be used to measure non-additive values.
263 //
264 // Here's how you might report memory usage of the heap objects used
265 // in application.
266 func ExampleMeter_observableGauge() {
267 if _, err := meter.Int64ObservableGauge(
268 "memory.heap",
269 metric.WithDescription(
270 "Memory usage of the allocated heap objects.",
271 ),
272 metric.WithUnit("By"),
273 metric.WithInt64Callback(func(_ context.Context, o metric.Int64Observer) error {
274 var m runtime.MemStats
275 runtime.ReadMemStats(&m)
276 o.Observe(int64(m.HeapAlloc))
277 return nil
278 }),
279 ); err != nil {
280 panic(err)
281 }
282 }
283
284 // You can add Attributes by using the [WithAttributeSet] and [WithAttributes] options.
285 //
286 // Here's how you might add the HTTP status code attribute to your recordings.
287 func ExampleMeter_attributes() {
288 apiCounter, err := meter.Int64UpDownCounter(
289 "api.finished.counter",
290 metric.WithDescription("Number of finished API calls."),
291 metric.WithUnit("{call}"),
292 )
293 if err != nil {
294 panic(err)
295 }
296 http.HandleFunc("/", func(_ http.ResponseWriter, r *http.Request) {
297 // do some work in an API call and set the response HTTP status code
298 statusCode := http.StatusOK
299
300 apiCounter.Add(r.Context(), 1,
301 metric.WithAttributes(semconv.HTTPResponseStatusCode(statusCode)))
302 })
303 }