go / expert
Snippet
Aufrufstapel-Frame-Extraktion mit runtime.Callers
Tiefe Fehlerdiagnose und benutzerdefinierte Observability-Tools erfordern oft die programmatische Inspektion von Aufrufstapeln ohne externe Bibliotheken. Die Kombination von `runtime.Callers` und `runtime.CallersFrames` dekodiert Programmzähler (PCs) in lesbare Funktionsnamen, Dateipfade und Zeilennummern unter Berücksichtigung von Inlining.
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()}
Erklärung
1
n := runtime.Callers(skip+1, pc)
Befüllt das Slice mit Programmzählern von Stack-Frames und überspringt die angegebene Anzahl an Aufrufebenen.
2
frames := runtime.CallersFrames(pc[:n])
Erzeugt einen Frame-Iterator, der Programmzähler-Adressen korrekt in Quellcode-Symbole umwandelt.