go / expert
Snippet
Stack Trace Frame Extraction with runtime.Callers
Deep error tracing and custom observability tools often require programmatic inspection of execution call stacks without third-party libraries. Using `runtime.Callers` combined with `runtime.CallersFrames` decodes program counters (PCs) into human-readable function names, file paths, and line numbers while correctly accounting for inlined function frames.
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
33
34
35
36
37
package mainimport ("fmt""runtime")type StackFrame struct {Function stringFile stringLine int}func CaptureCaller(skip int) StackFrame {pc := make([]uintptr, 1)n := runtime.Callers(skip+1, pc)if n == 0 {return StackFrame{}}frames := runtime.CallersFrames(pc[:n])frame, _ := frames.Next()return StackFrame{Function: frame.Function,File: frame.File,Line: frame.Line,}}func TraceableError() {frame := CaptureCaller(1)fmt.Printf("Error occurred at %s in %s:%d\n", frame.Function, frame.File, frame.Line)}func main() {TraceableError()}
Breakdown
1
n := runtime.Callers(skip+1, pc)
Fills the slice with program counters of call stack frames, skipping the specified depth of callers.
2
frames := runtime.CallersFrames(pc[:n])
Creates a frame iterator that accurately expands program counter addresses into source code symbols.