Skip to content

Commit

Permalink
Add FilterFieldKey to zaptest/observer
Browse files Browse the repository at this point in the history
Adds functionality to filter zap.Field by key. This makes testing for
field existence regardless of value more convenient.

resolves #816
  • Loading branch information
r-hang committed Mar 22, 2021
1 parent 89e3820 commit fab73a8
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
12 changes: 12 additions & 0 deletions zaptest/observer/observer.go
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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("a", 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

0 comments on commit fab73a8

Please sign in to comment.