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

     1  package xlog
     2  
     3  import (
     4  	"context"
     5  	"testing"
     6  	"time"
     7  
     8  	mredisv2 "github.com/alicebob/miniredis/v2"
     9  	redisv9 "github.com/redis/go-redis/v9"
    10  	"github.com/stretchr/testify/require"
    11  	"go.uber.org/zap"
    12  	"go.uber.org/zap/zapcore"
    13  )
    14  
    15  func TestGoRedisXLogger_ParentLogLevelChanged(t *testing.T) {
    16  	var (
    17  		parentLogger XLogger         = nil
    18  		logger       *GoRedisXLogger = nil
    19  	)
    20  	logger.Printf(context.TODO(), "test %d", 123)
    21  
    22  	opts := []XLoggerOption{
    23  		WithXLoggerLevel(LogLevelDebug),
    24  		WithXLoggerEncoder(JSON),
    25  		WithXLoggerTimeEncoder(zapcore.ISO8601TimeEncoder),
    26  		WithXLoggerLevelEncoder(zapcore.CapitalLevelEncoder),
    27  	}
    28  	parentLogger = NewXLogger(opts...)
    29  	logger = NewGoRedisXLogger(parentLogger)
    30  	parentLogger.IncreaseLogLevel(zapcore.ErrorLevel)
    31  	parentLogger.Debug("abc")
    32  	logger.Printf(context.TODO(), "test %d", 123)
    33  	parentLogger.IncreaseLogLevel(zapcore.DebugLevel)
    34  	parentLogger.Debug("abc")
    35  	logger.Printf(context.TODO(), "test %d", 123)
    36  	logger.Printf(context.TODO(), "test failed: %d", 123)
    37  	_ = parentLogger.Sync()
    38  	require.Panics(t, func() {
    39  		parentLogger = &xLogger{}
    40  		logger = NewGoRedisXLogger(parentLogger)
    41  	})
    42  }
    43  
    44  func TestGoRedisXLogger_MiniRedis(t *testing.T) {
    45  	var (
    46  		parentLogger XLogger         = nil
    47  		logger       *GoRedisXLogger = nil
    48  	)
    49  	opts := []XLoggerOption{
    50  		WithXLoggerLevel(LogLevelDebug),
    51  		WithXLoggerEncoder(JSON),
    52  		WithXLoggerTimeEncoder(zapcore.ISO8601TimeEncoder),
    53  		WithXLoggerLevelEncoder(zapcore.CapitalLevelEncoder),
    54  	}
    55  	parentLogger = NewXLogger(opts...)
    56  	logger = NewGoRedisXLogger(parentLogger)
    57  
    58  	const addr = "127.0.0.1:6379"
    59  	mredis := mredisv2.NewMiniRedis()
    60  	defer func() { mredis.Close() }()
    61  	go func() {
    62  		err := mredis.StartAddr(addr)
    63  		require.NoError(t, err)
    64  	}()
    65  
    66  	redisv9.SetLogger(logger)
    67  	rclient := redisv9.NewClient(&redisv9.Options{
    68  		Addr:     addr,
    69  		Password: "",
    70  		DB:       0,
    71  	})
    72  	defer func() { _ = rclient.Close() }()
    73  	rclient.Set(context.TODO(), "abc", "123", 0)
    74  	cmd := rclient.BLPop(context.TODO(), 1*time.Millisecond, "abc")
    75  	_, err := cmd.Result()
    76  	require.Error(t, err)
    77  	parentLogger.Debug("go redis", zap.Any("cmd", cmd.String()))
    78  	_ = parentLogger.Sync()
    79  }