-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathstack_trace.go
More file actions
86 lines (78 loc) · 2.09 KB
/
Copy pathstack_trace.go
File metadata and controls
86 lines (78 loc) · 2.09 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package agilepool
import (
"bufio"
"bytes"
"fmt"
"os"
"runtime"
)
// Stack returns formatted call stack info including file, line, PC, and source code.
//
// skip: frames to skip (1 = skip Stack itself, 2 = also skip caller)
//
// Example output:
//
// /home/user/main.go:25 (0x45a6f8)
// main.main: fmt.Println("hello world")
// /home/user/main.go:30 (0x45a8a2)
// main.testFunc
//
// Notes:
// - Requires readable source files, otherwise shows "Unknown"
// - Same consecutive files omit repeating source lines
// - Performs file I/O, not recommended for frequent calls in production
func Stack(skip int) []byte {
buf := new(bytes.Buffer)
var lastFile string
dunno := "Unknown"
// Iterate through call stack frames
for i := skip; ; i++ {
pc, file, line, ok := runtime.Caller(i)
if !ok {
break // Reached top of stack
}
// Print file, line number, and PC address
fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc)
// Print source line only for new files to avoid duplication
if file != lastFile {
sourceLine, err := readNthLine(file, line-1)
if err != nil {
sourceLine = dunno
}
fmt.Fprintf(buf, "\t%s: %s\n", function(pc), sourceLine)
lastFile = file
} else {
// Same file, just print function name
fmt.Fprintf(buf, "\t%s\n", function(pc))
}
}
return buf.Bytes()
}
// function returns the function name for given program counter (PC).
// Returns "unknown" if no function info is found (e.g., inlined or optimized).
func function(pc uintptr) string {
fn := runtime.FuncForPC(pc)
if fn == nil {
return "unknown"
}
return fn.Name()
}
// readNthLine reads line n (0-indexed) from the given file.
// Returns error if file cannot be opened, read fails, or line doesn't exist.
// Note: Opens file and scans from beginning each call - not efficient for frequent use.
func readNthLine(file string, n int) (string, error) {
f, err := os.Open(file)
if err != nil {
return "", err
}
defer f.Close()
scanner := bufio.NewScanner(f)
lineNum := 0
for scanner.Scan() {
if lineNum == n {
return scanner.Text(), nil
}
lineNum++
}
return "", scanner.Err()
}