Runtime Metrics Snapshot Read
List runtime/metrics names, then read heap and goroutine counters into a snapshot and branch on the value kind.
Code
package main
import (
"fmt"
"runtime/metrics"
"strings"
)
func main() {
// All lists every metric this Go runtime exposes
descriptions := metrics.All()
fmt.Println("available metrics:", len(descriptions))
gcCycles := 0
for _, d := range descriptions {
if strings.HasPrefix(d.Name, "/gc/cycles/") {
gcCycles++
}
}
fmt.Println("gc cycle metrics:", gcCycles)
// Read fills a snapshot for the requested metric names
samples := []metrics.Sample{
{Name: "/memory/classes/heap/objects:bytes"},
{Name: "/sched/goroutines:goroutines"},
}
metrics.Read(samples)
for _, sample := range samples {
fmt.Println(sample.Name, "kind:", sample.Value.Kind())
if sample.Value.Kind() == metrics.KindUint64 {
fmt.Println(sample.Name, "value:", sample.Value.Uint64())
}
}
}Inside the snippet
Structurally, expect the function main and nothing else.
Repetition is confined to for _, d := range descriptions — the rest of the file is straight-line.
Caveats
- Entirely standard-library — copy it in and it runs.
Putting it to use
Entry signature: func main()
Look for the available metrics:, gc cycle metrics: prefixes when the file runs; they tie each line to its step.
Core lines
for _, d := range descriptions {
if strings.HasPrefix(d.Name, "/gc/cycles/") {
gcCycles++
}
}
for _, sample := range samples {
fmt.Println(sample.Name, "kind:", sample.Value.Kind())
if sample.Value.Kind() == metrics.KindUint64 {
fmt.Println(sample.Name, "value:", sample.Value.Uint64())
}
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does Runtime Metrics Snapshot Read print when run?
- Running the file directly is enough — expect labeled output lines such as `available metrics:`, `gc cycle metrics:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.