2019-01-03 19:04:23 +00:00
|
|
|
// +build !binary_log
|
|
|
|
|
|
|
|
package pkgerrors
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2023-05-15 12:07:32 +00:00
|
|
|
"fmt"
|
2019-01-03 19:04:23 +00:00
|
|
|
"regexp"
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
2022-11-03 15:18:09 +00:00
|
|
|
"tuxpa.in/a/zlog"
|
2019-01-03 19:04:23 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestLogStack(t *testing.T) {
|
2022-03-20 19:19:42 +00:00
|
|
|
zlog.ErrorStackMarshaler = MarshalStack
|
2019-01-03 19:04:23 +00:00
|
|
|
|
|
|
|
out := &bytes.Buffer{}
|
2022-03-20 19:19:42 +00:00
|
|
|
log := zlog.New(out)
|
2019-01-03 19:04:23 +00:00
|
|
|
|
2023-05-15 12:07:32 +00:00
|
|
|
err := fmt.Errorf("from error: %w", errors.New("error message"))
|
2019-01-03 19:04:23 +00:00
|
|
|
log.Log().Stack().Err(err).Msg("")
|
|
|
|
|
|
|
|
got := out.String()
|
2023-05-15 12:07:32 +00:00
|
|
|
want := `\{"stack":\[\{"func":"TestLogStack","line":"21","source":"stacktrace_test.go"\},.*\],"error":"from error: error message"\}\n`
|
2019-01-03 19:04:23 +00:00
|
|
|
if ok, _ := regexp.MatchString(want, got); !ok {
|
|
|
|
t.Errorf("invalid log output:\ngot: %v\nwant: %v", got, want)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-23 22:01:01 +00:00
|
|
|
func TestLogStackFromContext(t *testing.T) {
|
2022-03-20 19:19:42 +00:00
|
|
|
zlog.ErrorStackMarshaler = MarshalStack
|
2021-03-23 22:01:01 +00:00
|
|
|
|
|
|
|
out := &bytes.Buffer{}
|
2022-03-20 19:19:42 +00:00
|
|
|
log := zlog.New(out).With().Stack().Logger() // calling Stack() on log context instead of event
|
2021-03-23 22:01:01 +00:00
|
|
|
|
2023-05-15 12:07:32 +00:00
|
|
|
err := fmt.Errorf("from error: %w", errors.New("error message"))
|
2021-03-23 22:01:01 +00:00
|
|
|
log.Log().Err(err).Msg("") // not explicitly calling Stack()
|
|
|
|
|
|
|
|
got := out.String()
|
2023-05-15 12:07:32 +00:00
|
|
|
want := `\{"stack":\[\{"func":"TestLogStackFromContext","line":"37","source":"stacktrace_test.go"\},.*\],"error":"from error: error message"\}\n`
|
2021-03-23 22:01:01 +00:00
|
|
|
if ok, _ := regexp.MatchString(want, got); !ok {
|
|
|
|
t.Errorf("invalid log output:\ngot: %v\nwant: %v", got, want)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-01-03 19:04:23 +00:00
|
|
|
func BenchmarkLogStack(b *testing.B) {
|
2022-03-20 19:19:42 +00:00
|
|
|
zlog.ErrorStackMarshaler = MarshalStack
|
2019-01-03 19:04:23 +00:00
|
|
|
out := &bytes.Buffer{}
|
2022-03-20 19:19:42 +00:00
|
|
|
log := zlog.New(out)
|
2019-01-03 19:04:23 +00:00
|
|
|
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()
|
|
|
|
}
|
|
|
|
}
|