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 FilterFieldKey to zaptest/observer #928

Merged
merged 1 commit into from Mar 23, 2021
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 12 additions & 0 deletions zaptest/observer/observer.go
Expand Up @@ -104,6 +104,18 @@ func (o *ObservedLogs) FilterField(field zapcore.Field) *ObservedLogs {
})
}

// FilterFieldKey filters entries to those that have the specified key.
func (o *ObservedLogs) FilterFieldKey(key string) *ObservedLogs {
return o.filter(func(e LoggedEntry) bool {
for _, ctxField := range e.Context {
if ctxField.Key == key {
return true
}
}
return false
})
}

func (o *ObservedLogs) filter(match func(LoggedEntry) bool) *ObservedLogs {
o.mu.RLock()
defer o.mu.RUnlock()
Expand Down
13 changes: 13 additions & 0 deletions zaptest/observer/observer_test.go
Expand Up @@ -149,6 +149,14 @@ func TestFilters(t *testing.T) {
Entry: zapcore.Entry{Level: zap.InfoLevel, Message: "any slice"},
Context: []zapcore.Field{zap.Any("slice", []string{"a"})},
},
{
Entry: zapcore.Entry{Level: zap.InfoLevel, Message: "msg 2"},
Context: []zapcore.Field{zap.Int("b", 2), zap.Namespace("filterMe")},
},
{
Entry: zapcore.Entry{Level: zap.InfoLevel, Message: "any slice"},
Context: []zapcore.Field{zap.Any("filterMe", []string{"b"})},
},
}

logger, sink := New(zap.InfoLevel)
Expand Down Expand Up @@ -206,6 +214,11 @@ func TestFilters(t *testing.T) {
filtered: sink.FilterField(zap.Any("slice", []string{"a"})),
want: logs[6:7],
},
{
msg: "filter field key",
filtered: sink.FilterFieldKey("filterMe"),
want: logs[7:9],
},
}

for _, tt := range tests {
Expand Down