From 0f38511ea8303b42007b5bdf7b85ebd6fafc833f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20Mart=C3=ADnez=20Trivi=C3=B1o?= Date: Mon, 7 Nov 2022 07:24:41 +0100 Subject: [PATCH] fix(filter): filter out keyvals if keyFunc is provided (#2484) --- log/filter.go | 16 +++++++--------- log/filter_test.go | 13 +++++++++++-- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/log/filter.go b/log/filter.go index ab5723770..993fa926e 100644 --- a/log/filter.go +++ b/log/filter.go @@ -64,20 +64,18 @@ func (f *Filter) Log(level Level, keyvals ...interface{}) error { if level < f.level { return nil } - // fkv is used to provide a slice to contains both logger.prefix and keyvals for filter - var fkv []interface{} + // prefixkv contains the slice of arguments defined as prefixes during the log initialization + var prefixkv []interface{} l, ok := f.logger.(*logger) if ok && len(l.prefix) > 0 { - fkv = make([]interface{}, 0, len(l.prefix)+len(keyvals)) - fkv = append(fkv, l.prefix...) - fkv = append(fkv, keyvals...) + prefixkv = make([]interface{}, 0, len(l.prefix)) + prefixkv = append(prefixkv, l.prefix...) } - if !ok { - fkv = keyvals - } - if f.filter != nil && f.filter(level, fkv...) { + + if f.filter != nil && (f.filter(level, prefixkv...) || f.filter(level, keyvals...)) { return nil } + if len(f.key) > 0 || len(f.value) > 0 { for i := 0; i < len(keyvals); i += 2 { v := i + 1 diff --git a/log/filter_test.go b/log/filter_test.go index d3c8d5485..3e36deac1 100644 --- a/log/filter_test.go +++ b/log/filter_test.go @@ -102,13 +102,19 @@ func TestFilterFuncWitchLoggerPrefix(t *testing.T) { want: "", }, { + // Filtered value logger: NewFilter(With(NewStdLogger(buf), "caller", "caller"), FilterFunc(testFilterFuncWithLoggerPrefix)), - want: "INFO caller=caller msg=msg\n", + want: "INFO caller=caller msg=msg filtered=***\n", + }, + { + // NO prefix + logger: NewFilter(With(NewStdLogger(buf)), FilterFunc(testFilterFuncWithLoggerPrefix)), + want: "INFO msg=msg filtered=***\n", }, } for _, tt := range tests { - err := tt.logger.Log(LevelInfo, "msg", "msg") + err := tt.logger.Log(LevelInfo, "msg", "msg", "filtered", "true") if err != nil { t.Fatal("err should be nil") } @@ -128,6 +134,9 @@ func testFilterFuncWithLoggerPrefix(level Level, keyvals ...interface{}) bool { if keyvals[i] == "prefix" { return true } + if keyvals[i] == "filtered" { + keyvals[i+1] = fuzzyStr + } } return false }