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 EmptyFields method to remove all the fileds from logger #575

Merged
merged 6 commits into from
Mar 6, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

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

GRbit marked this conversation as resolved.
Show resolved Hide resolved
# 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.
GRbit marked this conversation as resolved.
Show resolved Hide resolved
func (c Context) EmptyFields() Context {
GRbit marked this conversation as resolved.
Show resolved Hide resolved
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) {
GRbit marked this conversation as resolved.
Show resolved Hide resolved
out := &bytes.Buffer{}
ctx := New(out).With().
Str("string", "foo").
Stringer("stringer", net.IP{127, 0, 0, 1}).
Stringer("stringer_nil", nil).
EmptyFields().
GRbit marked this conversation as resolved.
Show resolved Hide resolved
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