How to Monitor System Resources from Go

Monitor Go system resources like memory and goroutines using the built-in runtime/metrics package.

Use the runtime/metrics package to read real-time system resource data like CPU usage, memory allocation, and goroutine counts without external dependencies.

package main

import (
	"fmt"
	"runtime/metrics"
)

func main() {
	ms := metrics.Read([]metrics.Sample{
		{Name: "/gc/cycles/automatic:gc-cycles"},
		{Name: "/sched/goroutines:goroutines"},
		{Name: "/memory/classes/heap-objects:bytes"},
	})

	for _, m := range ms {
		fmt.Printf("%s: %v\n", m.Name, m.Value.Uint64())
	}
}