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

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