github.com/pingcap/br@v5.3.0-alpha.0.20220125034240-ec59c7b6ce30+incompatible/pkg/lightning/log/filter.go (about)

     1  // Copyright 2021 PingCAP, Inc. Licensed under Apache-2.0.
     2  
     3  package log
     4  
     5  import (
     6  	"strings"
     7  
     8  	"go.uber.org/zap/zapcore"
     9  )
    10  
    11  var _ zapcore.Core = (*FilterCore)(nil)
    12  
    13  // FilterCore is a zapcore.Core implementation, it filters log by path-qualified
    14  // package name.
    15  type FilterCore struct {
    16  	zapcore.Core
    17  	filters []string
    18  }
    19  
    20  // NewFilterCore returns a FilterCore.
    21  //
    22  // Example, filter TiDB's log, `NewFilterCore(core, "github.com/pingcap/tidb/")`.
    23  // Note, must set AddCaller() to the logger.
    24  func NewFilterCore(core zapcore.Core, filteredPackages ...string) *FilterCore {
    25  	return &FilterCore{
    26  		Core:    core,
    27  		filters: filteredPackages,
    28  	}
    29  }
    30  
    31  // With adds structured context to the Core.
    32  func (f *FilterCore) With(fields []zapcore.Field) zapcore.Core {
    33  	return &FilterCore{
    34  		Core:    f.Core.With(fields),
    35  		filters: f.filters,
    36  	}
    37  }
    38  
    39  // Check overrides wrapper core.Check and adds itself to zapcore.CheckedEntry.
    40  func (f *FilterCore) Check(entry zapcore.Entry, ce *zapcore.CheckedEntry) *zapcore.CheckedEntry {
    41  	if f.Enabled(entry.Level) {
    42  		return ce.AddCore(entry, f)
    43  	}
    44  	return ce
    45  }
    46  
    47  // Write filters entry by checking if entry's Caller.Function matches filtered
    48  // package path.
    49  func (f *FilterCore) Write(entry zapcore.Entry, fields []zapcore.Field) error {
    50  	for i := range f.filters {
    51  		// Caller.Function is a package path-qualified function name.
    52  		if strings.Contains(entry.Caller.Function, f.filters[i]) {
    53  			return nil
    54  		}
    55  	}
    56  	return f.Core.Write(entry, fields)
    57  }