diff --git a/metric/example_test.go b/metric/example_test.go index 162b206e245..acb5c70f5f9 100644 --- a/metric/example_test.go +++ b/metric/example_test.go @@ -7,6 +7,7 @@ import ( "context" "database/sql" "fmt" + "math/rand" "net/http" "runtime" "time" @@ -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.