Skip to content

Commit

Permalink
Support logger for print stack trace (#195)
Browse files Browse the repository at this point in the history
Fixes #171
  • Loading branch information
sayboras committed Aug 22, 2020
1 parent 55df21f commit d6944a4
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 8 deletions.
9 changes: 7 additions & 2 deletions recovery.go
Expand Up @@ -19,7 +19,7 @@ type recoveryHandler struct {

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

func parseRecoveryOptions(h http.Handler, opts ...RecoveryOption) http.Handler {
Expand Down Expand Up @@ -86,6 +86,11 @@ func (h recoveryHandler) log(v ...interface{}) {
}

if h.printStack {
debug.PrintStack()
stack := string(debug.Stack())
if h.logger != nil {
h.logger.Println(stack)
} else {
log.Println(stack)
}
}
}
26 changes: 20 additions & 6 deletions recovery_test.go
Expand Up @@ -30,15 +30,29 @@ func TestRecoveryLoggerWithCustomLogger(t *testing.T) {
var buf bytes.Buffer
var logger = log.New(&buf, "", log.LstdFlags)

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

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

if !strings.Contains(buf.String(), "Unexpected error!") {
t.Fatalf("Got log %#v, wanted substring %#v", buf.String(), "Unexpected error!")
}
recovery := handler(handlerFunc)
recovery.ServeHTTP(httptest.NewRecorder(), newRequest("GET", "/subdir/asdf"))

if !strings.Contains(buf.String(), "Unexpected error!") {
t.Fatalf("Got log %#v, wanted substring %#v", buf.String(), "Unexpected error!")
}
})

t.Run("With print stack enabled", func(t *testing.T) {
handler := RecoveryHandler(RecoveryLogger(logger), PrintRecoveryStack(true))

recovery := handler(handlerFunc)
recovery.ServeHTTP(httptest.NewRecorder(), newRequest("GET", "/subdir/asdf"))

if !strings.Contains(buf.String(), "runtime/debug.Stack") {
t.Fatalf("Got log %#v, wanted substring %#v", buf.String(), "runtime/debug.Stack")
}
})
}

0 comments on commit d6944a4

Please sign in to comment.