1
0
mirror of https://github.com/go-kratos/kratos.git synced 2025-01-22 03:38:41 +02:00
kratos/log/filter.go

97 lines
2.0 KiB
Go
Raw Normal View History

2021-06-14 00:14:32 +08:00
package log
// FilterOption is filter option.
type FilterOption func(*Filter)
const fuzzyStr = "***"
2021-06-14 10:14:23 +08:00
// FilterLevel with filter level.
2021-06-14 00:14:32 +08:00
func FilterLevel(level Level) FilterOption {
return func(opts *Filter) {
2021-06-14 01:11:24 +08:00
opts.level = level
2021-06-14 00:14:32 +08:00
}
}
2021-06-14 10:14:23 +08:00
// FilterKey with filter key.
func FilterKey(key ...string) FilterOption {
return func(o *Filter) {
2021-06-14 00:14:32 +08:00
for _, v := range key {
2021-06-14 10:14:23 +08:00
o.key[v] = struct{}{}
2021-06-14 00:14:32 +08:00
}
}
}
2021-06-14 10:14:23 +08:00
// FilterValue with filter value.
func FilterValue(value ...string) FilterOption {
return func(o *Filter) {
2021-06-14 00:14:32 +08:00
for _, v := range value {
2021-06-14 10:14:23 +08:00
o.value[v] = struct{}{}
2021-06-14 00:14:32 +08:00
}
}
}
2021-06-14 10:14:23 +08:00
// FilterFunc with filter func.
func FilterFunc(f func(level Level, keyvals ...interface{}) bool) FilterOption {
return func(o *Filter) {
o.filter = f
2021-06-14 00:14:32 +08:00
}
}
2021-06-14 10:14:23 +08:00
// Filter is a logger filter.
type Filter struct {
logger Logger
level Level
2021-06-14 10:50:22 +08:00
key map[interface{}]struct{}
value map[interface{}]struct{}
2021-06-14 10:14:23 +08:00
filter func(level Level, keyvals ...interface{}) bool
}
2021-06-14 00:14:32 +08:00
// NewFilter new a logger filter.
func NewFilter(logger Logger, opts ...FilterOption) *Filter {
2021-06-14 10:14:23 +08:00
options := Filter{
logger: logger,
2021-06-14 10:50:22 +08:00
key: make(map[interface{}]struct{}),
value: make(map[interface{}]struct{}),
2021-06-14 10:14:23 +08:00
}
2021-06-14 00:14:32 +08:00
for _, o := range opts {
o(&options)
}
return &options
}
2021-06-14 11:12:58 +08:00
// Log Print log by level and keyvals.
2021-06-14 10:14:23 +08:00
func (f *Filter) Log(level Level, keyvals ...interface{}) error {
if level < f.level {
return nil
2021-06-14 00:14:32 +08:00
}
// fkv is used to provide a slice to contains both logger.prefix and keyvals for filter
var fkv []interface{}
2022-05-21 16:23:09 +08:00
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...)
}
if !ok {
fkv = keyvals
}
if f.filter != nil && f.filter(level, fkv...) {
2021-06-14 10:14:23 +08:00
return nil
2021-06-14 00:14:32 +08:00
}
if len(f.key) > 0 || len(f.value) > 0 {
for i := 0; i < len(keyvals); i += 2 {
v := i + 1
if v >= len(keyvals) {
continue
}
if _, ok := f.key[keyvals[i]]; ok {
keyvals[v] = fuzzyStr
}
if _, ok := f.value[keyvals[v]]; ok {
keyvals[v] = fuzzyStr
}
2021-06-14 00:14:32 +08:00
}
}
2021-06-14 10:14:23 +08:00
return f.logger.Log(level, keyvals...)
2021-06-14 00:14:32 +08:00
}