Skip to content

Commit d6944a4

Browse files
authored
Support logger for print stack trace (#195)
Fixes #171
1 parent 55df21f commit d6944a4

File tree

2 files changed

+27
-8
lines changed

2 files changed

+27
-8
lines changed

recovery.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ type recoveryHandler struct {
1919

2020
// RecoveryOption provides a functional approach to define
2121
// configuration for a handler; such as setting the logging
22-
// whether or not to print strack traces on panic.
22+
// whether or not to print stack traces on panic.
2323
type RecoveryOption func(http.Handler)
2424

2525
func parseRecoveryOptions(h http.Handler, opts ...RecoveryOption) http.Handler {
@@ -86,6 +86,11 @@ func (h recoveryHandler) log(v ...interface{}) {
8686
}
8787

8888
if h.printStack {
89-
debug.PrintStack()
89+
stack := string(debug.Stack())
90+
if h.logger != nil {
91+
h.logger.Println(stack)
92+
} else {
93+
log.Println(stack)
94+
}
9095
}
9196
}

recovery_test.go

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,15 +30,29 @@ func TestRecoveryLoggerWithCustomLogger(t *testing.T) {
3030
var buf bytes.Buffer
3131
var logger = log.New(&buf, "", log.LstdFlags)
3232

33-
handler := RecoveryHandler(RecoveryLogger(logger), PrintRecoveryStack(false))
3433
handlerFunc := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
3534
panic("Unexpected error!")
3635
})
3736

38-
recovery := handler(handlerFunc)
39-
recovery.ServeHTTP(httptest.NewRecorder(), newRequest("GET", "/subdir/asdf"))
37+
t.Run("Without print stack", func(t *testing.T) {
38+
handler := RecoveryHandler(RecoveryLogger(logger), PrintRecoveryStack(false))
4039

41-
if !strings.Contains(buf.String(), "Unexpected error!") {
42-
t.Fatalf("Got log %#v, wanted substring %#v", buf.String(), "Unexpected error!")
43-
}
40+
recovery := handler(handlerFunc)
41+
recovery.ServeHTTP(httptest.NewRecorder(), newRequest("GET", "/subdir/asdf"))
42+
43+
if !strings.Contains(buf.String(), "Unexpected error!") {
44+
t.Fatalf("Got log %#v, wanted substring %#v", buf.String(), "Unexpected error!")
45+
}
46+
})
47+
48+
t.Run("With print stack enabled", func(t *testing.T) {
49+
handler := RecoveryHandler(RecoveryLogger(logger), PrintRecoveryStack(true))
50+
51+
recovery := handler(handlerFunc)
52+
recovery.ServeHTTP(httptest.NewRecorder(), newRequest("GET", "/subdir/asdf"))
53+
54+
if !strings.Contains(buf.String(), "runtime/debug.Stack") {
55+
t.Fatalf("Got log %#v, wanted substring %#v", buf.String(), "runtime/debug.Stack")
56+
}
57+
})
4458
}

0 commit comments

Comments
 (0)