Skip to content

Commit cbf4a73

Browse files
committed
Allow customization of the stack trace format
1 parent 32c405d commit cbf4a73

1 file changed

Lines changed: 21 additions & 11 deletions

File tree

stacktrace.go

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,25 @@ import (
88
"strings"
99
)
1010

11+
// DefaultCallersFormatter is the default formatter for [Callers].
12+
var DefaultCallersFormatter = func(c Callers, w io.Writer) {
13+
for _, frame := range c.Frames() {
14+
io.WriteString(w, "at ")
15+
frame.writeFrame(w)
16+
io.WriteString(w, "\n")
17+
}
18+
}
19+
20+
// DefaultFrameFormatter is the default formatter for [Frame].
21+
var DefaultFrameFormatter = func(f Frame, w io.Writer) {
22+
io.WriteString(w, shortname(f.Function))
23+
io.WriteString(w, " (")
24+
io.WriteString(w, f.File)
25+
io.WriteString(w, ":")
26+
io.WriteString(w, strconv.Itoa(f.Line))
27+
io.WriteString(w, ")")
28+
}
29+
1130
const stackTraceDepth = 128
1231

1332
// StackTrace extracts the stack trace from the provided error.
@@ -127,12 +146,7 @@ func (f Frame) Format(s fmt.State, verb rune) {
127146

128147
// writeFrame writes a formatted stack frame to the given [io.Writer].
129148
func (f Frame) writeFrame(w io.Writer) {
130-
io.WriteString(w, shortname(f.Function))
131-
io.WriteString(w, " (")
132-
io.WriteString(w, f.File)
133-
io.WriteString(w, ":")
134-
io.WriteString(w, strconv.Itoa(f.Line))
135-
io.WriteString(w, ")")
149+
DefaultFrameFormatter(f, w)
136150
}
137151

138152
// Callers represents a list of program counters from the
@@ -194,11 +208,7 @@ func (c Callers) Format(s fmt.State, verb rune) {
194208

195209
// writeTrace writes the stack trace to the provided [io.Writer].
196210
func (c Callers) writeTrace(w io.Writer) {
197-
for _, frame := range c.Frames() {
198-
io.WriteString(w, "at ")
199-
frame.writeFrame(w)
200-
io.WriteString(w, "\n")
201-
}
211+
DefaultCallersFormatter(c, w)
202212
}
203213

204214
// callers captures the current stack trace, skipping the specified

0 commit comments

Comments
 (0)