From 81fd1a37589cd7f9f5784ead5354b83e1743e1ed Mon Sep 17 00:00:00 2001 From: Matthew Penner Date: Sun, 6 Dec 2020 15:55:35 -0700 Subject: [PATCH] Make logged stacktraces more useful --- loggers/cli/cli.go | 56 +++++++++++++--------------------------------- 1 file changed, 15 insertions(+), 41 deletions(-) diff --git a/loggers/cli/cli.go b/loggers/cli/cli.go index 0710cdf..c469675 100644 --- a/loggers/cli/cli.go +++ b/loggers/cli/cli.go @@ -71,51 +71,25 @@ func (h *Handler) HandleLog(e *log.Entry) error { continue } - var br = color2.New(color2.Bold, color2.FgRed) if err, ok := e.Fields.Get("error").(error); ok { - fmt.Fprintf(h.Writer, "\n%s%+v\n\n", br.Sprintf("Stacktrace:"), getErrorStack(err, false)) + br := color2.New(color2.Bold, color2.FgRed) + + if e, ok := errors.Cause(err).(tracer); ok { + st := e.StackTrace() + + l := len(st) + if l > 10 { + l = 10 + } + + fmt.Fprintf(h.Writer, "\n%s%+v\n\n", br.Sprintf("Stacktrace:"), st[0:l]) + } else { + fmt.Fprintf(h.Writer, "\n%s\n%+v\n\n", br.Sprintf("Stacktrace:"), err) + } } else { - fmt.Fprintf(h.Writer, "\n%s%+v\n\n", br.Sprintf("Invalid Error:"), err) + fmt.Printf("\n\nINVALID ERROR\n\n") } } return nil } - -func getErrorStack(err error, i bool) errors.StackTrace { - e, ok := err.(tracer) - if !ok { - if i { - // Just abort out of this and return a stacktrace leading up to this point. It isn't perfect - // but it'll at least include what function lead to this being called which we can then handle. - if e, ok = errors.WithMessage(err, "failed to generate stacktrace for caught error").(tracer); ok { - return e.StackTrace() - } - - // The errors.WrapIf did not return a interface compatible with `tracer`, so - // we don't have an easy way to get the stacktrace, this should probably be changed - // at some point, but without this the application may panic when handling some errors. - return nil - } - - return getErrorStack(errors.WithMessage(err, err.Error()), true) - } - - st := e.StackTrace() - - l := len(st) - // If this was an internal stack generation we're going to skip over the top four items in the stack - // trace since they'll point to the error that was generated by this function. - f := 0 - if i { - f = 5 - } - - if i && l > 9 { - l = 9 - } else if !i && l > 5 { - l = 5 - } - - return st[f:l] -}