Skip to content

Commit

Permalink
zaptest: add ability to filter observer logs by logger name (#1452)
Browse files Browse the repository at this point in the history
This is useful for assertions on logs in a particular named path,
currently this is only possible through calls to Filter but it is more
verbose.

Added a FilterLoggerName function that plays nicely with the other
filters:

	zapLogs.FilterLoggerName("my.logger").FilterMessage("hello")

---------

Signed-off-by: Mauri de Souza Meneguzzo <mauri870@gmail.com>
Co-authored-by: Sung Yoon Whang <sungyoonwhang@gmail.com>
  • Loading branch information
mauri870 and sywhang committed Jul 22, 2024
1 parent 8dcd020 commit f9b9f66
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
7 changes: 7 additions & 0 deletions zaptest/observer/observer.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,13 @@ func (o *ObservedLogs) FilterMessage(msg string) *ObservedLogs {
})
}

// FilterLoggerName filters entries to those logged through logger with the specified logger name.
func (o *ObservedLogs) FilterLoggerName(name string) *ObservedLogs {
return o.Filter(func(e LoggedEntry) bool {
return e.LoggerName == name
})
}

// FilterMessageSnippet filters entries to those that have a message containing the specified snippet.
func (o *ObservedLogs) FilterMessageSnippet(snippet string) *ObservedLogs {
return o.Filter(func(e LoggedEntry) bool {
Expand Down
9 changes: 9 additions & 0 deletions zaptest/observer/observer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,10 @@ func TestFilters(t *testing.T) {
Entry: zapcore.Entry{Level: zap.ErrorLevel, Message: "warp core breach"},
Context: []zapcore.Field{zap.Int("b", 42)},
},
{
Entry: zapcore.Entry{Level: zap.ErrorLevel, Message: "msg", LoggerName: "my.logger"},
Context: []zapcore.Field{zap.Int("b", 42)},
},
}

logger, sink := New(zap.InfoLevel)
Expand Down Expand Up @@ -251,6 +255,11 @@ func TestFilters(t *testing.T) {
filtered: sink.FilterLevelExact(zap.WarnLevel),
want: logs[9:10],
},
{
msg: "filter logger name",
filtered: sink.FilterLoggerName("my.logger"),
want: logs[11:12],
},
}

for _, tt := range tests {
Expand Down

0 comments on commit f9b9f66

Please sign in to comment.