Skip to content

Commit

Permalink
Add EmptyFields method to remove all the fileds from logger (#575)
Browse files Browse the repository at this point in the history
Co-authored-by: Olivier Poitrey <rs@rhapsodyk.net>
Co-authored-by: tlipoca9 <160737620+tlipoca9@users.noreply.github.com>
  • Loading branch information
3 people committed Mar 6, 2024
1 parent e5edd4b commit 74cf37a
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
6 changes: 6 additions & 0 deletions context.go
Expand Up @@ -409,6 +409,12 @@ func (c Context) Any(key string, i interface{}) Context {
return c.Interface(key, i)
}

// Reset removes all the context fields.
func (c Context) Reset() Context {
c.l.context = enc.AppendBeginMarker(make([]byte, 0, 500))
return c
}

type callerHook struct {
callerSkipFrameCount int
}
Expand Down
19 changes: 19 additions & 0 deletions log_test.go
Expand Up @@ -145,6 +145,25 @@ func TestWith(t *testing.T) {
}
}

func TestWithReset(t *testing.T) {
out := &bytes.Buffer{}
ctx := New(out).With().
Str("string", "foo").
Stringer("stringer", net.IP{127, 0, 0, 1}).
Stringer("stringer_nil", nil).
Reset().
Bytes("bytes", []byte("bar")).
Hex("hex", []byte{0x12, 0xef}).
Uint64("uint64", 10).
Float64("float64", 12.30303).
Ctx(context.Background())
log := ctx.Logger()
log.Log().Msg("")
if got, want := decodeIfBinaryToString(out.Bytes()), `{"bytes":"bar","hex":"12ef","uint64":10,"float64":12.30303}`+"\n"; got != want {
t.Errorf("invalid log output:\ngot: %v\nwant: %v", got, want)
}
}

func TestFieldsMap(t *testing.T) {
out := &bytes.Buffer{}
log := New(out)
Expand Down

0 comments on commit 74cf37a

Please sign in to comment.