Make logged stacktraces more useful

This commit is contained in:
Matthew Penner 2020-12-06 15:55:35 -07:00
parent 83f0d2c953
commit 81fd1a3758

View File

@ -71,51 +71,25 @@ func (h *Handler) HandleLog(e *log.Entry) error {
continue continue
} }
var br = color2.New(color2.Bold, color2.FgRed)
if err, ok := e.Fields.Get("error").(error); ok { 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 { } else {
fmt.Fprintf(h.Writer, "\n%s%+v\n\n", br.Sprintf("Invalid Error:"), err) fmt.Printf("\n\nINVALID ERROR\n\n")
} }
} }
return nil 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]
}