Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: add stacktrace when recover. #5654

Merged
merged 1 commit into from
Oct 18, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 21 additions & 3 deletions pkg/middlewares/recovery/recovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package recovery
import (
"context"
"net/http"
"runtime"

"github.com/containous/traefik/v2/pkg/log"
"github.com/containous/traefik/v2/pkg/middlewares"
Expand All @@ -28,13 +29,30 @@ func New(ctx context.Context, next http.Handler, name string) (http.Handler, err
}

func (re *recovery) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
defer recoverFunc(middlewares.GetLoggerCtx(req.Context(), re.name, typeName), rw)
defer recoverFunc(middlewares.GetLoggerCtx(req.Context(), re.name, typeName), rw, req)
re.next.ServeHTTP(rw, req)
}

func recoverFunc(ctx context.Context, rw http.ResponseWriter) {
func recoverFunc(ctx context.Context, rw http.ResponseWriter, r *http.Request) {
if err := recover(); err != nil {
log.FromContext(ctx).Errorf("Recovered from panic in http handler: %+v", err)
if !shouldLogPanic(err) {
log.FromContext(ctx).Debugf("Request has been aborted [%s - %s]: %v", r.RemoteAddr, r.URL, err)
return
}

log.FromContext(ctx).Errorf("Recovered from panic in HTTP handler [%s - %s]: %+v", r.RemoteAddr, r.URL, err)

const size = 64 << 10
buf := make([]byte, size)
buf = buf[:runtime.Stack(buf, false)]
log.FromContext(ctx).Errorf("Stack: %s", buf)

http.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}

// https://github.com/golang/go/blob/a0d6420d8be2ae7164797051ec74fa2a2df466a1/src/net/http/server.go#L1761-L1775
// https://github.com/golang/go/blob/c33153f7b416c03983324b3e8f869ce1116d84bc/src/net/http/httputil/reverseproxy.go#L284
func shouldLogPanic(panicValue interface{}) bool {
return panicValue != nil && panicValue != http.ErrAbortHandler
}