Capture Stack Frames With runtime.Callers

Walk the call stack with runtime.Callers and runtime.CallersFrames to log function names, files, and line numbers for diagnostics.

GoResilience

Code

gosnippet
29 lines
package main

import (
	"fmt"
	"runtime"
)

func inner() {
	// skip 2:跳过 runtime.Callers 与 inner 自身
	pcs := make([]uintptr, 16)
	n := runtime.Callers(2, pcs)
	frames := runtime.CallersFrames(pcs[:n])
	for {
		frame, more := frames.Next()
		fmt.Printf("%s %s:%d\n", frame.Function, frame.File, frame.Line)
		if !more {
			break
		}
	}
}

func middle() {
	inner()
}

func main() {
	middle()
	fmt.Println("captured frames above")
}

What the file does

Capture Stack Frames With runtime.Callers is built around the functions inner, middle and main.

Repetition is confined to for — the rest of the file is straight-line.

Applying it

Entry signature: func inner()

Running the file prints labeled results such as captured frames above — each operation’s effect is visible in the output.

main sequences middle; executing the file runs that flow once.

Statements that matter

func middle() {
inner()
}
func main() {
middle()
fmt.Println("captured frames above")
}
pcs := make([]uintptr, 16)

Interactive Tools for This Topic

FAQ

What does Capture Stack Frames With runtime.Callers print when run?
The script runs standalone; its 1 labeled outputs include `captured frames above`.