Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add stacktrace to Context #630

Merged
merged 1 commit into from
Jan 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading