fix(log): FilterFunc keyvals lost logger prefix (#1901)

pull/1902/head
Cluas 3 years ago committed by GitHub
parent d4c0c57681
commit 13208d7908
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 13
      log/filter.go
  2. 42
      log/filter_test.go

@ -64,7 +64,18 @@ func (f *Filter) Log(level Level, keyvals ...interface{}) error {
if level < f.level { if level < f.level {
return nil 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 return nil
} }
if len(f.key) > 0 || len(f.value) > 0 { if len(f.key) > 0 || len(f.value) > 0 {

@ -1,6 +1,7 @@
package log package log
import ( import (
"bytes"
"io" "io"
"testing" "testing"
) )
@ -89,3 +90,44 @@ func testFilterFunc(level Level, keyvals ...interface{}) bool {
} }
return false 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
}

Loading…
Cancel
Save