Debug Stack Capture Goroutine

Capture the current goroutine stack with runtime/debug.Stack, then pick the calling frame out of it without panicking the process.

GoResilience

Code

gosnippet
28 lines
package main

import (
	"fmt"
	"runtime/debug"
	"strings"
)

func captureStack() string {
	// debug.Stack returns the current goroutine trace without crashing
	lines := strings.Split(string(debug.Stack()), "\n")
	for _, line := range lines {
		if strings.Contains(line, "loadConfig") {
			return strings.TrimSpace(line)
		}
	}
	return "loadConfig frame not found"
}

func loadConfig() error {
	return fmt.Errorf("config missing; called from %s", captureStack())
}

func main() {
	err := loadConfig()
	fmt.Println("error:", err)
	fmt.Println("has frame:", strings.Contains(err.Error(), "loadConfig"))
}

Ordering of the operations

Debug Stack Capture Goroutine comes down to the functions captureStack, loadConfig and main.

A single loop drives the file — for _, line := range lines.

What to watch for

  • No external packages — everything relies on the language’s built-in APIs.

Using it

Signature: func captureStack() string

Running the file prints labeled results such as error:, has frame: — each operation’s effect is visible in the output.

Running the file executes main, which drives loadConfig in order.

Key statements

return fmt.Errorf("config missing; called from %s", captureStack())
func captureStack() string {
// debug.Stack returns the current goroutine trace without crashing
lines := strings.Split(string(debug.Stack()), "\n")
for _, line := range lines {
if strings.Contains(line, "loadConfig") {
return strings.TrimSpace(line)
}
}
return "loadConfig frame not found"
}
func main() {
err := loadConfig()
fmt.Println("error:", err)
fmt.Println("has frame:", strings.Contains(err.Error(), "loadConfig"))
}

Interactive Tools for This Topic

FAQ

What does Debug Stack Capture Goroutine print when run?
Running the file directly is enough — expect labeled output lines such as `error:`, `has frame:`.