Skip to content

Commit

Permalink
fix: Include stack trace only when log level >= debug
Browse files Browse the repository at this point in the history
  • Loading branch information
aeneasr committed Mar 13, 2020
1 parent 98c6ed9 commit 8e5f29a
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
3 changes: 2 additions & 1 deletion error_default.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ import (
"io"
"net/http"

"github.com/ory/x/errorsx"
"github.com/pkg/errors"

"github.com/ory/x/errorsx"
)

type DefaultError struct {
Expand Down
22 changes: 15 additions & 7 deletions error_reporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ type stackTracer interface {
StackTrace() errors.StackTrace
}

type logLeveler interface {
GetLevel() logrus.Level
}

func DefaultErrorReporter(logger logrus.FieldLogger, args ...interface{}) func(w http.ResponseWriter, r *http.Request, code int, err error) {
return func(w http.ResponseWriter, r *http.Request, code int, err error) {
if logger == nil {
Expand All @@ -28,19 +32,23 @@ func DefaultErrorReporter(logger logrus.FieldLogger, args ...interface{}) func(w
}

func DefaultErrorLogger(logger logrus.FieldLogger, err error) logrus.FieldLogger {
trace := fmt.Sprintf("Stack trace could not be recovered from error type %s", reflect.TypeOf(err))
if e, ok := err.(stackTracer); ok {
trace = fmt.Sprintf("Stack trace: %+v", e.StackTrace())
}

richError := ToDefaultError(err, "")
return logger.
richLogger := logger.
WithField("request-id", richError.RequestID()).
WithField("trace", trace).
WithField("code", richError.StatusCode()).
WithField("reason", richError.Reason()).
WithField("debug", richError.Debug()).
WithField("details", richError.Details()).
WithField("status", richError.Status()).
WithError(err)

if leveler, ok := logger.(logLeveler); ok && leveler.GetLevel() >= logrus.DebugLevel {
if e, ok := err.(stackTracer); ok {
richLogger.WithField("trace", fmt.Sprintf("%+v", e.StackTrace()))
} else {
richLogger.WithField("trace", fmt.Sprintf("Stack trace could not be recovered from error type %s", reflect.TypeOf(err)))
}
}

return richLogger
}

0 comments on commit 8e5f29a

Please sign in to comment.