Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add example for synchronous gauge #5492

Merged
merged 12 commits into from
Jun 24, 2024
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 wordl applications, replace this to get the actual fan speed.
MrAlias marked this conversation as resolved.
Show resolved Hide resolved
return int64(1500 * rand.Intn(1000))
MrAlias marked this conversation as resolved.
Show resolved Hide resolved
}

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