From f9b9f66ea72d4e221f0249fef3b21430864cb2aa Mon Sep 17 00:00:00 2001 From: Mauri de Souza Meneguzzo Date: Mon, 22 Jul 2024 17:30:47 -0300 Subject: [PATCH] zaptest: add ability to filter observer logs by logger name (#1452) 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 Co-authored-by: Sung Yoon Whang --- zaptest/observer/observer.go | 7 +++++++ zaptest/observer/observer_test.go | 9 +++++++++ 2 files changed, 16 insertions(+) diff --git a/zaptest/observer/observer.go b/zaptest/observer/observer.go index f77f1308b..4f7ce0ec6 100644 --- a/zaptest/observer/observer.go +++ b/zaptest/observer/observer.go @@ -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 { diff --git a/zaptest/observer/observer_test.go b/zaptest/observer/observer_test.go index 0cf631c03..cbe167025 100644 --- a/zaptest/observer/observer_test.go +++ b/zaptest/observer/observer_test.go @@ -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) @@ -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 {