diff --git a/zaptest/observer/observer.go b/zaptest/observer/observer.go index ed36ba3be..9d54273f9 100644 --- a/zaptest/observer/observer.go +++ b/zaptest/observer/observer.go @@ -21,6 +21,7 @@ package observer import ( + "strings" "sync" "time" @@ -87,6 +88,13 @@ func (o *ObservedLogs) FilterMessage(msg string) *ObservedLogs { }) } +// 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 { + return strings.Contains(e.Message, snippet) + }) +} + // FilterField filters entries to those that have the specified field. func (o *ObservedLogs) FilterField(field zapcore.Field) *ObservedLogs { return o.filter(func(e LoggedEntry) bool { diff --git a/zaptest/observer/observer_test.go b/zaptest/observer/observer_test.go index e6fbe599c..b66851e7e 100644 --- a/zaptest/observer/observer_test.go +++ b/zaptest/observer/observer_test.go @@ -137,6 +137,10 @@ func TestFilters(t *testing.T) { Entry: zapcore.Entry{Level: zap.InfoLevel, Message: "log c"}, Context: []zapcore.Field{zap.Int("a", 1), zap.Namespace("ns"), zap.Int("a", 2)}, }, + { + Entry: zapcore.Entry{Level: zap.InfoLevel, Message: "msg 1"}, + Context: []zapcore.Field{zap.Int("a", 1), zap.Namespace("ns")}, + }, } logger, sink := New(zap.InfoLevel) @@ -174,6 +178,16 @@ func TestFilters(t *testing.T) { filtered: sink.FilterMessage("no match"), want: []LoggedEntry{}, }, + { + msg: "filter by snippet", + filtered: sink.FilterMessageSnippet("log"), + want: logs[0:4], + }, + { + msg: "filter by snippet and field", + filtered: sink.FilterMessageSnippet("a").FilterField(zap.Int("b", 2)), + want: logs[1:2], + }, } for _, tt := range tests {