You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
kratos/log/filter.go

86 lines
1.7 KiB

3 years ago
package log
// FilterOption is filter option.
type FilterOption func(*Filter)
const fuzzyStr = "***"
3 years ago
// FilterLevel with filter level.
3 years ago
func FilterLevel(level Level) FilterOption {
return func(opts *Filter) {
3 years ago
opts.level = level
3 years ago
}
}
3 years ago
// FilterKey with filter key.
func FilterKey(key ...string) FilterOption {
return func(o *Filter) {
3 years ago
for _, v := range key {
3 years ago
o.key[v] = struct{}{}
3 years ago
}
}
}
3 years ago
// FilterValue with filter value.
func FilterValue(value ...string) FilterOption {
return func(o *Filter) {
3 years ago
for _, v := range value {
3 years ago
o.value[v] = struct{}{}
3 years ago
}
}
}
3 years ago
// FilterFunc with filter func.
func FilterFunc(f func(level Level, keyvals ...interface{}) bool) FilterOption {
return func(o *Filter) {
o.filter = f
3 years ago
}
}
3 years ago
// Filter is a logger filter.
type Filter struct {
logger Logger
level Level
3 years ago
key map[interface{}]struct{}
value map[interface{}]struct{}
3 years ago
filter func(level Level, keyvals ...interface{}) bool
}
3 years ago
// NewFilter new a logger filter.
func NewFilter(logger Logger, opts ...FilterOption) *Filter {
3 years ago
options := Filter{
logger: logger,
3 years ago
key: make(map[interface{}]struct{}),
value: make(map[interface{}]struct{}),
3 years ago
}
3 years ago
for _, o := range opts {
o(&options)
}
return &options
}
3 years ago
// Log Print log by level and keyvals.
3 years ago
func (f *Filter) Log(level Level, keyvals ...interface{}) error {
if level < f.level {
return nil
3 years ago
}
3 years ago
if f.filter != nil && f.filter(level, keyvals...) {
return nil
3 years ago
}
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
}
3 years ago
}
}
3 years ago
return f.logger.Log(level, keyvals...)
3 years ago
}