Skip to content

Commit

Permalink
Add example for synchronous gauge (#5492)
Browse files Browse the repository at this point in the history
Added example for synchronous gauge

Related: #5414
  • Loading branch information
bagmeg authored Jun 24, 2024
1 parent f6a5aa2 commit a814b35
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions metric/example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"context"
"database/sql"
"fmt"
"math/rand"
"net/http"
"runtime"
"time"
Expand Down Expand Up @@ -142,6 +143,45 @@ func ExampleMeter_upDownCounter() {
}
}

// Gauges can be used to record non-additive values when changes occur.
//
// Here's how you might report the current speed of a cpu fan.
func ExampleMeter_gauge() {
speedGauge, err := meter.Int64Gauge(
"cpu.fan.speed",
metric.WithDescription("Speed of CPU fan"),
metric.WithUnit("RPM"),
)
if err != nil {
panic(err)
}

getCPUFanSpeed := func() int64 {
// Generates a random fan speed for demonstration purpose.
// In real world applications, replace this to get the actual fan speed.
return int64(1500 + rand.Intn(1000))
}

fanSpeedSubscription := make(chan int64, 1)
go func() {
defer close(fanSpeedSubscription)

for idx := 0; idx < 5; idx++ {
// Synchronous gauges are used when the measurement cycle is
// synchronous to an external change.
// Simulate that external cycle here.
time.Sleep(time.Duration(rand.Intn(3)) * time.Second)
fanSpeed := getCPUFanSpeed()
fanSpeedSubscription <- fanSpeed
}
}()

ctx := context.Background()
for fanSpeed := range fanSpeedSubscription {
speedGauge.Record(ctx, fanSpeed)
}
}

// Histograms are used to measure a distribution of values over time.
//
// Here's how you might report a distribution of response times for an HTTP handler.
Expand Down

0 comments on commit a814b35

Please sign in to comment.