Skip to content

Commit

Permalink
Add stacktrace to Context (#630)
Browse files Browse the repository at this point in the history
  • Loading branch information
mcdoker18 authored Jan 3, 2024
1 parent 3e8ae07 commit a9ec232
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 0 deletions.
16 changes: 16 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,22 @@ func (c Context) Errs(key string, errs []error) Context {

// Err adds the field "error" with serialized err to the logger context.
func (c Context) Err(err error) Context {
if c.l.stack && ErrorStackMarshaler != nil {
switch m := ErrorStackMarshaler(err).(type) {
case nil:
case LogObjectMarshaler:
c = c.Object(ErrorStackFieldName, m)
case error:
if m != nil && !isNilValue(m) {
c = c.Str(ErrorStackFieldName, m.Error())
}
case string:
c = c.Str(ErrorStackFieldName, m)
default:
c = c.Interface(ErrorStackFieldName, m)
}
}

return c.AnErr(ErrorFieldName, err)
}

Expand Down
1 change: 1 addition & 0 deletions diode/diode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package diode_test
import (
"bytes"
"fmt"
"io"
"log"
"os"
"testing"
Expand Down
1 change: 1 addition & 0 deletions hlog/hlog_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
Expand Down
16 changes: 16 additions & 0 deletions pkgerrors/stacktrace_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,22 @@ func TestLogStackFromContext(t *testing.T) {
}
}

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

err := fmt.Errorf("from error: %w", errors.New("error message"))
out := &bytes.Buffer{}
log := zerolog.New(out).With().Stack().Err(err).Logger() // calling Stack() on log context instead of event

log.Error().Msg("")

got := out.String()
want := `\{"level":"error","stack":\[\{"func":"TestLogStackFromContextWith","line":"66","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 a9ec232

Please sign in to comment.