Skip to content

Commit

Permalink
add EmptyFields method to remove all the fileds from logger
Browse files Browse the repository at this point in the history
  • Loading branch information
GRbit committed Aug 21, 2023
1 parent b81cc57 commit f4d949c
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ _obj
_test
tmp

# IDE config files
.idea
.vscode

# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
Expand Down
6 changes: 6 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,12 @@ func (c Context) Any(key string, i interface{}) Context {
return c.Interface(key, i)
}

// EmptyFields removes all the context fields.
func (c Context) EmptyFields() 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
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,25 @@ func TestWith(t *testing.T) {
}
}

func TestWithEmptyFields(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).
EmptyFields().
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 f4d949c

Please sign in to comment.