Commit 7dab6e0054d7ea9c7e325445b0bdde90571d4038
1 parent
8d63648a35
Exists in
master
call stack for error tracing
Showing
1 changed file
with
23 additions
and
10 deletions
Show diff stats
main.go
... | ... | @@ -89,19 +89,32 @@ func (l *Logger) Print(format string, v ...interface{}) { |
89 | 89 | fmt.Printf("%s: %s\n", time.Now().Format(dateTimeFormat), msg) |
90 | 90 | } |
91 | 91 | |
92 | -// CallerFilenameAndLineNumber ... | |
93 | -func CallerFilenameAndLineNumber() (string, int) { | |
94 | - _, path, line, _ := runtime.Caller(2) | |
95 | - file := filepath.Base(path) | |
96 | - return file, line | |
92 | +const MaxStackDepth = 10000 | |
93 | + | |
94 | +// CallStack | |
95 | +func CallStack() (stack string) { | |
96 | + callers := make([]uintptr, MaxStackDepth) // min 1 | |
97 | + stackDepth := runtime.Callers(2, callers) | |
98 | + frames := runtime.CallersFrames(callers) | |
99 | + | |
100 | + for i := 0; i < stackDepth; i++ { | |
101 | + if i >= 2 { // skip runtime and startup | |
102 | + frame, next := frames.Next() | |
103 | + stack += fmt.Sprintf("[%s %d]\n", frame.File, frame.Line) | |
104 | + if !next { | |
105 | + break | |
106 | + } | |
107 | + } | |
108 | + } | |
109 | + | |
110 | + return | |
97 | 111 | } |
98 | 112 | |
99 | 113 | // PrintTrace ... |
100 | 114 | func (l *Logger) PrintTrace(format string, v ...interface{}) { |
101 | - file, line := CallerFilenameAndLineNumber() | |
102 | - | |
115 | + stack := CallStack() | |
103 | 116 | msg := fmt.Sprintf(format, v...) |
104 | - fmt.Printf("%s: %s %d: %s\n", time.Now().Format(dateTimeFormat), file, line, msg) | |
117 | + fmt.Printf("%s:\n%s\n%s\n", time.Now().Format(dateTimeFormat), stack, msg) | |
105 | 118 | } |
106 | 119 | |
107 | 120 | // Trace ... |
... | ... | @@ -113,10 +126,10 @@ func (l *Logger) Trace(format string, v ...interface{}) { |
113 | 126 | l.mu.Lock() |
114 | 127 | defer l.mu.Unlock() |
115 | 128 | |
116 | - file, line := CallerFilenameAndLineNumber() | |
129 | + stack := CallStack() | |
117 | 130 | |
118 | 131 | msg := fmt.Sprintf(format, v...) |
119 | - s := fmt.Sprintf("%s: %s %d: %s\n", time.Now().Format(dateTimeFormat), file, line, msg) | |
132 | + s := fmt.Sprintf("%s:\n%s\n%s\n", time.Now().Format(dateTimeFormat), stack, msg) | |
120 | 133 | |
121 | 134 | if l.shouldSplit(len(s)) { |
122 | 135 | l.split() | ... | ... |