runtime Stack Dumps Goroutine Traces

runtime.Stack writes the current goroutine trace into a caller buffer, and the all=true variant dumps every goroutine for health diagnostics.

GoResilience

Code

gosnippet
21 lines
package main

import (
	"fmt"
	"runtime"
)

func main() {
	buf := make([]byte, 4096)
	// Stack dumps the calling goroutine's traces into the buffer
	n := runtime.Stack(buf, false)
	fmt.Printf("stack bytes: %d\n", n)

	// all=true walks every goroutine: useful for health diagnostics
	all := make([]byte, 8192)
	total := runtime.Stack(all, true)
	fmt.Printf("all goroutines bytes: %d\n", total)

	// the dump always begins with the goroutine header
	fmt.Println(string(buf[:16]))
}

How it works

runtime Stack Dumps Goroutine Traces reduces to the function main.

Caveats

  • Self-contained — imports go no further than what the runtime provides.

Using it

The one signature that matters here is func main()

The demo output is labeled (stack bytes:, all goroutines bytes:), so each line traces straight back to the statement that printed it.

The key statements that remain

buf := make([]byte, 4096)
all := make([]byte, 8192)

Interactive Tools for This Topic

FAQ

What does runtime Stack Dumps Goroutine Traces print when run?
The script runs standalone; its 2 labeled outputs include `stack bytes:`, `all goroutines bytes:`.