2021-12-20 14:31:31 +08:00
|
|
|
package logutil
|
|
|
|
|
|
|
|
import (
|
2022-03-10 08:46:06 +08:00
|
|
|
"io"
|
2021-12-20 14:31:31 +08:00
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
2022-01-21 07:36:06 +08:00
|
|
|
func NewFilter(levels []logrus.Level, filters ...string) logrus.Hook {
|
2021-12-20 14:31:31 +08:00
|
|
|
dl := logrus.New()
|
2022-03-10 08:46:06 +08:00
|
|
|
dl.SetOutput(io.Discard)
|
2021-12-20 14:31:31 +08:00
|
|
|
return &logsFilter{
|
2022-01-21 07:36:06 +08:00
|
|
|
levels: levels,
|
2021-12-20 14:31:31 +08:00
|
|
|
filters: filters,
|
|
|
|
discardLogger: dl,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type logsFilter struct {
|
2022-01-21 07:36:06 +08:00
|
|
|
levels []logrus.Level
|
2021-12-20 14:31:31 +08:00
|
|
|
filters []string
|
|
|
|
discardLogger *logrus.Logger
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *logsFilter) Levels() []logrus.Level {
|
2022-01-21 07:36:06 +08:00
|
|
|
return d.levels
|
2021-12-20 14:31:31 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (d *logsFilter) Fire(entry *logrus.Entry) error {
|
|
|
|
for _, f := range d.filters {
|
|
|
|
if strings.Contains(entry.Message, f) {
|
|
|
|
entry.Logger = d.discardLogger
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|