Runtime Metrics Snapshot Read

List runtime/metrics names, then read heap and goroutine counters into a snapshot and branch on the value kind.

GoResilience

Code

gosnippet
34 lines
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

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:`.