Skip to content

Commit

Permalink
Fix Context.Stack() (#303)
Browse files Browse the repository at this point in the history
  • Loading branch information
bvisness authored Mar 23, 2021
1 parent 72b5b1e commit f2cc3cf
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 9 deletions.
10 changes: 1 addition & 9 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -406,17 +406,9 @@ func (c Context) CallerWithSkipFrameCount(skipFrameCount int) Context {
return c
}

type stackTraceHook struct{}

func (sh stackTraceHook) Run(e *Event, level Level, msg string) {
e.Stack()
}

var sh = stackTraceHook{}

// Stack enables stack trace printing for the error passed to Err().
func (c Context) Stack() Context {
c.l = c.l.Hook(sh)
c.l.stack = true
return c
}

Expand Down
4 changes: 4 additions & 0 deletions log.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ type Logger struct {
sampler Sampler
context []byte
hooks []Hook
stack bool
}

// New creates a root logger with given output writer. If the output writer implements
Expand Down Expand Up @@ -425,6 +426,9 @@ func (l *Logger) newEvent(level Level, done func(string)) *Event {
if l.context != nil && len(l.context) > 1 {
e.buf = enc.AppendObjectData(e.buf, l.context)
}
if l.stack {
e.Stack()
}
return e
}

Expand Down
16 changes: 16 additions & 0 deletions pkgerrors/stacktrace_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,22 @@ func TestLogStack(t *testing.T) {
}
}

func TestLogStackFromContext(t *testing.T) {
zerolog.ErrorStackMarshaler = MarshalStack

out := &bytes.Buffer{}
log := zerolog.New(out).With().Stack().Logger() // calling Stack() on log context instead of event

err := errors.Wrap(errors.New("error message"), "from error")
log.Log().Err(err).Msg("") // not explicitly calling Stack()

got := out.String()
want := `\{"stack":\[\{"func":"TestLogStackFromContext","line":"36","source":"stacktrace_test.go"\},.*\],"error":"from error: error message"\}\n`
if ok, _ := regexp.MatchString(want, got); !ok {
t.Errorf("invalid log output:\ngot: %v\nwant: %v", got, want)
}
}

func BenchmarkLogStack(b *testing.B) {
zerolog.ErrorStackMarshaler = MarshalStack
out := &bytes.Buffer{}
Expand Down

0 comments on commit f2cc3cf

Please sign in to comment.