github.com/benz9527/xboot@v0.0.0-20240504061247-c23f15593274/xlog/goredis.go (about)

     1  package xlog
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"strings"
     7  
     8  	"go.uber.org/zap"
     9  	"go.uber.org/zap/zapcore"
    10  )
    11  
    12  type GoRedisXLogger struct {
    13  	logger XLogger
    14  }
    15  
    16  func (l *GoRedisXLogger) Printf(ctx context.Context, format string, v ...any) {
    17  	if l == nil || l.logger == nil {
    18  		return
    19  	}
    20  	log := fmt.Sprintf(format, v...)
    21  	if strings.Contains(log, "failed") {
    22  		l.logger.Logf(zapcore.ErrorLevel, log)
    23  		return
    24  	}
    25  	l.logger.Logf(zapcore.InfoLevel, log)
    26  }
    27  
    28  func NewGoRedisXLogger(logger XLogger) *GoRedisXLogger {
    29  	l := &xLogger{}
    30  	l.logger.Store(logger.
    31  		zap().
    32  		Named("GoRedis").
    33  		WithOptions(zap.WrapCore(func(core zapcore.Core) zapcore.Core {
    34  			if core == nil {
    35  				panic("[XLogger] core is nil")
    36  			}
    37  			cc, ok := core.(xLogCore)
    38  			if !ok {
    39  				panic("[XLogger] core is not XLogCore")
    40  			}
    41  			var err error
    42  			if mc, ok := cc.(xLogMultiCore); ok && mc != nil {
    43  				if cc, err = WrapCores(mc, componentCoreEncoderCfg()); err != nil {
    44  					panic(err)
    45  				}
    46  			} else {
    47  				if cc, err = WrapCore(cc, componentCoreEncoderCfg()); err != nil {
    48  					panic(err)
    49  				}
    50  			}
    51  			return cc
    52  		})),
    53  	)
    54  	return &GoRedisXLogger{
    55  		logger: l,
    56  	}
    57  }