go / expert
Snippet
Extracting Stack Frames with Low Overhead using runtime.Callers and runtime.CallersFrames
Direct allocation of program counters using runtime.Callers coupled with runtime.CallersFrames provides an efficient mechanism for capturing structured call stack frames without parsing unformatted string stacks from runtime/debug.Stack.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package mainimport ("fmt""runtime")type TraceError struct {Msg stringFrames []runtime.Frame}func CaptureError(msg string) *TraceError {pc := make([]uintptr, 10)n := runtime.Callers(2, pc)frames := runtime.CallersFrames(pc[:n])var errFrames []runtime.Framefor {frame, more := frames.Next()errFrames = append(errFrames, frame)if !more {break}}return &TraceError{Msg: msg, Frames: errFrames}}func main() {err := CaptureError("critical system failure")fmt.Printf("Error: %s, Top frame: %s\n", err.Msg, err.Frames[0].Function)}
Breakdown
1
pc := make([]uintptr, 10)
Allocates a buffer to hold program counter instruction pointers.
2
n := runtime.Callers(2, pc)
Fills the slice with stack program counters, skipping callers to ignore internal frame setup.
3
frames := runtime.CallersFrames(pc[:n])
Translates raw program counters into structured function name, file, and line details.