diff --git a/log/filter.go b/log/filter.go index 9258f3f36..9ef87ddf1 100644 --- a/log/filter.go +++ b/log/filter.go @@ -64,7 +64,18 @@ func (f *Filter) Log(level Level, keyvals ...interface{}) error { if level < f.level { return nil } - if f.filter != nil && f.filter(level, keyvals...) { + // fkv is used to provide a slice to contains both logger.prefix and keyvals for filter + var fkv []interface{} + if l, ok := f.logger.(*logger); ok { + if len(l.prefix) > 0 { + fkv = make([]interface{}, 0, len(l.prefix)+len(keyvals)) + fkv = append(fkv, l.prefix...) + fkv = append(fkv, keyvals...) + } + } else { + fkv = keyvals + } + if f.filter != nil && f.filter(level, fkv...) { return nil } if len(f.key) > 0 || len(f.value) > 0 { diff --git a/log/filter_test.go b/log/filter_test.go index 4a8b249f8..d3c8d5485 100644 --- a/log/filter_test.go +++ b/log/filter_test.go @@ -1,6 +1,7 @@ package log import ( + "bytes" "io" "testing" ) @@ -89,3 +90,44 @@ func testFilterFunc(level Level, keyvals ...interface{}) bool { } return false } + +func TestFilterFuncWitchLoggerPrefix(t *testing.T) { + buf := new(bytes.Buffer) + tests := []struct { + logger Logger + want string + }{ + { + logger: NewFilter(With(NewStdLogger(buf), "caller", "caller", "prefix", "whaterver"), FilterFunc(testFilterFuncWithLoggerPrefix)), + want: "", + }, + { + logger: NewFilter(With(NewStdLogger(buf), "caller", "caller"), FilterFunc(testFilterFuncWithLoggerPrefix)), + want: "INFO caller=caller msg=msg\n", + }, + } + + for _, tt := range tests { + err := tt.logger.Log(LevelInfo, "msg", "msg") + if err != nil { + t.Fatal("err should be nil") + } + got := buf.String() + if got != tt.want { + t.Fatalf("filter should catch prefix, want %s, got %s.", tt.want, got) + } + buf.Reset() + } +} + +func testFilterFuncWithLoggerPrefix(level Level, keyvals ...interface{}) bool { + if level == LevelWarn { + return true + } + for i := 0; i < len(keyvals); i += 2 { + if keyvals[i] == "prefix" { + return true + } + } + return false +}