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

82 lines
1.6 KiB

4 years ago
package log
// FilterOption is filter option.
type FilterOption func(*Filter)
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 f.level > level {
return nil
4 years ago
}
4 years ago
if f.filter != nil && f.filter(level, keyvals...) {
return nil
4 years ago
}
4 years ago
for i := 0; i < len(keyvals); i += 2 {
4 years ago
if _, ok := f.key[keyvals[i]]; ok {
4 years ago
keyvals[i+1] = "***"
}
4 years ago
vi := i + 1
if vi >= len(keyvals) {
continue
}
4 years ago
if _, ok := f.value[keyvals[vi]]; ok {
4 years ago
keyvals[i+1] = "***"
4 years ago
}
}
4 years ago
return f.logger.Log(level, keyvals...)
4 years ago
}