From 8e5f29a3e2adcefb56f57c693d7db8313aefb2ee Mon Sep 17 00:00:00 2001 From: aeneasr Date: Fri, 13 Mar 2020 01:43:37 +0100 Subject: [PATCH] fix: Include stack trace only when log level >= debug Related https://github.com/ory/oathkeeper/issues/37 --- error_default.go | 3 ++- error_reporter.go | 22 +++++++++++++++------- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/error_default.go b/error_default.go index 8ae31bd..82db4a7 100644 --- a/error_default.go +++ b/error_default.go @@ -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 { diff --git a/error_reporter.go b/error_reporter.go index 2c82417..20d83fa 100644 --- a/error_reporter.go +++ b/error_reporter.go @@ -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 { @@ -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 }