Repository navigation
Expand file tree
/
Copy pathstacktrace.go
More file actions
executable file
·329 lines (298 loc) · 9.11 KB
/
Copy pathstacktrace.go
File metadata and controls
executable file
·329 lines (298 loc) · 9.11 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
// logfile/stacktrace.go - Error stack trace functionality
package logfile
import (
"errors"
"fmt"
"io"
"log"
"path"
"runtime"
"strconv"
"strings"
"sync"
)
// stackPool holds reusable slices of uintptr for stack trace capture.
// This sync.Pool helps reduce memory allocations and GC pressure
// when capturing stack traces frequently.
var stackPool = sync.Pool{
New: func() interface{} {
// Pre-allocate a slice with a reasonable default capacity (32 frames).
s := make([]uintptr, 32)
return &s
},
}
// Frame represents a single program counter in a stack trace.
type Frame uintptr
// pc returns the program counter for this frame.
// It subtracts 1 because runtime.Callers and runtime.FuncForPC
// use different conventions for the program counter. This adjustment
// makes runtime.FuncForPC return the correct file/line for the call site.
func (f Frame) pc() uintptr { return uintptr(f) - 1 }
// file returns the full path to the file for this Frame's pc.
func (f Frame) file() string {
// Find the function associated with this program counter.
fn := runtime.FuncForPC(f.pc())
if fn == nil {
return "unknown"
}
// Get the file and line number from the function.
file, _ := fn.FileLine(f.pc())
return file
}
// line returns the line number of source code for this Frame's pc.
func (f Frame) line() int {
fn := runtime.FuncForPC(f.pc())
if fn == nil {
return 0
}
_, line := fn.FileLine(f.pc())
return line
}
// name returns the full name of this function, including package path.
func (f Frame) name() string {
fn := runtime.FuncForPC(f.pc())
if fn == nil {
return "unknown"
}
return fn.Name()
}
// Format implements the fmt.Formatter interface for formatting a Frame.
// This allows custom formatting verbs like %+v when printing.
//
// Verbs:
//
// %s - prints the file name (e.g., "stacktrace.go")
// %+s - prints the full function name and file path (e.g., "main.go\n\t/path/to/main.go")
// %d - prints the line number
// %n - prints the simple function name (e.g., "MyFunction")
// %v - prints file:line (e.g., "stacktrace.go:100")
// %+v - prints function name, file, and line (e.g., "main.go\n\t/path/to/main.go:100")
func (f Frame) Format(s fmt.State, verb rune) {
var err error
switch verb {
case 's':
switch {
case s.Flag('+'):
// Verbose: print function name and full file path.
_, err = io.WriteString(s, f.name())
if err != nil {
log.Printf("Error writing name: %v", err) // Log the error
return
}
_, err = io.WriteString(s, "\n\t")
if err != nil {
log.Printf("Error writing newline: %v", err) // Log the error
return
}
_, err = io.WriteString(s, f.file())
if err != nil {
log.Printf("Error writing file: %v", err) // Log the error
return
}
default:
// Default: print base file name.
_, err = io.WriteString(s, path.Base(f.file()))
if err != nil {
log.Printf("Error writing file base name: %v", err) // Log the error
return
}
}
case 'd':
// Print line number.
_, err = io.WriteString(s, strconv.Itoa(f.line()))
if err != nil {
log.Printf("Error writing line number: %v", err) // Log the error
return
}
case 'n':
// Print simple function name (without package path).
_, err = io.WriteString(s, funcname(f.name()))
if err != nil {
log.Printf("Error writing function name: %v", err) // Log the error
return
}
case 'v':
// Default verb: format as "file:line"
f.Format(s, 's') // 's' gives file name
_, err = io.WriteString(s, ":")
if err != nil {
log.Printf("Error writing colon: %v", err) // Log the error
return
}
f.Format(s, 'd') // 'd' gives line number
}
}
// MarshalText implements the encoding.TextMarshaler interface.
// This formats a stack frame as text, useful for logging or JSON encoding.
func (f Frame) MarshalText() ([]byte, error) {
name := f.name()
if name == "unknown" {
return []byte(name), nil
}
// Format as "functionName /path/to/file:line"
return []byte(fmt.Sprintf("%s %s:%d", name, f.file(), f.line())), nil
}
// StackTrace is a stack of Frames from innermost (most recent call) to outermost.
type StackTrace []Frame
// Format implements the fmt.Formatter interface for formatting a StackTrace.
//
// Verbs:
//
// %v - prints a collapsed, single-line slice of frames
// %+v - prints a full, multi-line stack trace
func (st StackTrace) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
switch {
case s.Flag('+'):
// Verbose: print each frame on a new line with its details.
for _, f := range st {
io.WriteString(s, "\n")
f.Format(s, verb)
}
case s.Flag('#'):
// Go-syntax representation.
fmt.Fprintf(s, "%#v", []Frame(st))
default:
// Default: format as a single-line slice.
st.formatSlice(s, verb)
}
case 's':
// Format as a single-line slice.
st.formatSlice(s, verb)
}
}
// formatSlice is a helper to format the stack trace as a single-line slice of Frames.
func (st StackTrace) formatSlice(s fmt.State, verb rune) {
io.WriteString(s, "[")
for i, f := range st {
if i > 0 {
io.WriteString(s, " ")
}
f.Format(s, verb)
}
io.WriteString(s, "]")
}
// stack represents a raw stack of program counters.
// This is the internal representation before it's converted to a StackTrace.
type stack []uintptr
// Format implements the fmt.Formatter interface for a raw stack.
// It's primarily used to print the full trace when formatting a stackError
// with the %+v verb.
func (s *stack) Format(st fmt.State, verb rune) {
switch verb {
case 'v':
switch {
case st.Flag('+'):
// Verbose: format each PC as a full Frame.
for _, pc := range *s {
f := Frame(pc)
fmt.Fprintf(st, "\n%+v", f)
}
}
}
}
// StackTrace converts the raw stack of PCs into a user-facing StackTrace (slice of Frames).
func (s *stack) StackTrace() StackTrace {
f := make([]Frame, len(*s))
for i := 0; i < len(f); i++ {
f[i] = Frame((*s)[i])
}
return f
}
// callersMu protects the stackPool and runtime.Callers from concurrent access.
var callersMu sync.Mutex
// callers captures the current goroutine's stack trace.
// It uses the stackPool to avoid allocating a new slice for program counters each time.
func callers() *stack {
callersMu.Lock()
defer callersMu.Unlock()
// Get a slice from the pool.
pcsPtr := stackPool.Get().(*[]uintptr)
pcs := *pcsPtr
// Capture the stack trace.
// Skip 3 frames:
// 0: runtime.Callers
// 1: logfile.callers (this function)
// 2: logfile.WithStack (the function that called this)
n := runtime.Callers(3, pcs)
// Create a new stack of the exact size needed.
result := make(stack, n)
copy(result, pcs[0:n])
// Return the slice to the pool for reuse.
stackPool.Put(pcsPtr)
return &result
}
// funcname removes the path prefix component of a function's name.
// e.g., "github.com/my/package.MyFunction" becomes "MyFunction".
func funcname(name string) string {
i := strings.LastIndex(name, "/")
name = name[i+1:]
i = strings.Index(name, ".")
return name[i+1:]
}
// stackError wraps an error with a stack trace.
// It implements the error interface and the errors.Wrapper interface.
type stackError struct {
error // The original error.
*stack // The stack trace captured when the error was wrapped.
once sync.Once // Ensures stack is captured only once (not currently used, but good practice).
}
// Unwrap returns the underlying error, implementing the errors.Wrapper interface.
// This allows errors.Is and errors.As to work correctly.
func (w *stackError) Unwrap() error { return w.error }
// Format implements the fmt.Formatter interface for stackError.
// This allows custom formatting, especially for %+v.
func (w *stackError) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
if s.Flag('+') {
// Verbose: print the underlying error's verbose format,
// then print our own stack trace.
fmt.Fprintf(s, "%+v", w.Unwrap())
w.stack.Format(s, verb) // This will print the full stack
return
}
fallthrough
case 's':
// Default: print the underlying error's message.
io.WriteString(s, w.Error())
case 'q':
// Quoted: print the underlying error's message, quoted.
fmt.Fprintf(s, "%q", w.Error())
}
}
// WithStack annotates err with a stack trace at the point WithStack was called.
// If err is nil, it returns nil.
// If err already has a stack trace (as determined by HasStack), it returns err unmodified.
func WithStack(err error) error {
if err == nil {
return nil
}
// If error already has a stack, don't add another.
if HasStack(err) {
return err
}
// Wrap the error with a new stackError.
return &stackError{
error: err,
stack: callers(), // Capture the stack trace now.
}
}
// GetStack finds the first error in the chain that has a stack trace
// (i.e., is a *stackError) and returns the StackTrace if found.
func GetStack(err error) (StackTrace, bool) {
var target *stackError
// Use errors.As to search the error chain for a stackError.
ok := errors.As(err, &target)
if !ok {
return nil, false
}
return target.StackTrace(), true
}
// HasStack returns true if any error in err's chain has a stacktrace.
func HasStack(err error) bool {
var target *stackError
// errors.As checks if err or any of its wrapped errors are of type *stackError.
return errors.As(err, &target)
}