mirror of
https://github.com/go-kratos/kratos.git
synced 2025-01-28 03:57:02 +02:00
fix(log): FilterFunc keyvals lost logger prefix (#1901)
This commit is contained in:
parent
d4c0c57681
commit
13208d7908
@ -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 {
|
||||
|
@ -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
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user