pkgerrors: remove fmt dep

This commit is contained in:
Olivier Poitrey 2019-01-02 13:19:14 -08:00
parent adb19ff852
commit 2988c1e444
2 changed files with 47 additions and 5 deletions

View File

@ -1,8 +1,6 @@
package pkgerrors
import (
"fmt"
"github.com/pkg/errors"
)
@ -12,6 +10,36 @@ var (
StackSourceFunctionName = "func"
)
type state struct {
b []byte
}
// Write implement fmt.Formatter interface.
func (s *state) Write(b []byte) (n int, err error) {
s.b = b
return len(b), nil
}
// Width implement fmt.Formatter interface.
func (s *state) Width() (wid int, ok bool) {
return 0, false
}
// Precision implement fmt.Formatter interface.
func (s *state) Precision() (prec int, ok bool) {
return 0, false
}
// Flag implement fmt.Formatter interface.
func (s *state) Flag(c int) bool {
return false
}
func frameField(f errors.Frame, s *state, c rune) string {
f.Format(s, c)
return string(s.b)
}
// MarshalStack implements pkg/errors stack trace marshaling.
//
// zerolog.ErrorStackMarshaler = MarshalStack
@ -25,12 +53,13 @@ func MarshalStack(err error) interface{} {
} else {
return nil
}
s := &state{}
out := make([]map[string]string, 0, len(st))
for _, frame := range st {
out = append(out, map[string]string{
StackSourceFileName: fmt.Sprintf("%s", frame),
StackSourceLineName: fmt.Sprintf("%d", frame),
StackSourceFunctionName: fmt.Sprintf("%n", frame),
StackSourceFileName: frameField(frame, s, 's'),
StackSourceLineName: frameField(frame, s, 'd'),
StackSourceFunctionName: frameField(frame, s, 'n'),
})
}
return out

View File

@ -26,3 +26,16 @@ func TestLogStack(t *testing.T) {
t.Errorf("invalid log output:\ngot: %v\nwant: %v", got, want)
}
}
func BenchmarkLogStack(b *testing.B) {
zerolog.ErrorStackMarshaler = MarshalStack
out := &bytes.Buffer{}
log := zerolog.New(out)
err := errors.Wrap(errors.New("error message"), "from error")
b.ReportAllocs()
for i := 0; i < b.N; i++ {
log.Log().Stack().Err(err).Msg("")
out.Reset()
}
}