github.com/benz9527/xboot@v0.0.0-20240504061247-c23f15593274/xlog/common_core_test.go (about) 1 package xlog 2 3 import ( 4 "testing" 5 6 "github.com/stretchr/testify/require" 7 "go.uber.org/zap" 8 "go.uber.org/zap/zapcore" 9 ) 10 11 func TestCommonCore(t *testing.T) { 12 var cc xLogCore = &commonCore{} 13 require.Nil(t, cc.outEncoder()) 14 require.Nil(t, cc.writeSyncer()) 15 require.Nil(t, cc.levelEncoder()) 16 require.Nil(t, cc.timeEncoder()) 17 require.Nil(t, cc.(*commonCore).lvlEnabler) 18 require.Nil(t, cc.(*commonCore).core) 19 20 lvlEnabler := zap.NewAtomicLevelAt(LogLevelDebug.zapLevel()) 21 cc = &commonCore{ 22 lvlEnabler: &lvlEnabler, 23 lvlEnc: zapcore.CapitalLevelEncoder, 24 tsEnc: zapcore.ISO8601TimeEncoder, 25 ws: getOutWriterByType(logOutWriterType(5)), 26 enc: getEncoderByType(logEncoderType(6)), 27 } 28 29 config := zapcore.EncoderConfig{ 30 MessageKey: "msg", 31 LevelKey: "lvl", 32 EncodeLevel: cc.(*commonCore).lvlEnc, 33 TimeKey: "ts", 34 EncodeTime: cc.(*commonCore).tsEnc, 35 CallerKey: "callAt", 36 EncodeCaller: zapcore.ShortCallerEncoder, 37 FunctionKey: "fn", 38 NameKey: "component", 39 EncodeName: zapcore.FullNameEncoder, 40 StacktraceKey: coreKeyIgnored, 41 } 42 cc.(*commonCore).core = zapcore.NewCore(cc.(*commonCore).enc(config), cc.(*commonCore).ws, cc.(*commonCore).lvlEnabler) 43 require.NotNil(t, cc.outEncoder()) 44 require.NotNil(t, cc.writeSyncer()) 45 require.NotNil(t, cc.levelEncoder()) 46 require.NotNil(t, cc.timeEncoder()) 47 require.NotNil(t, cc.(*commonCore).lvlEnabler) 48 require.NotNil(t, cc.(*commonCore).core) 49 50 require.True(t, cc.Enabled(zapcore.DebugLevel)) 51 require.True(t, cc.Enabled(zapcore.InfoLevel)) 52 require.True(t, cc.Enabled(zapcore.WarnLevel)) 53 require.True(t, cc.Enabled(zapcore.ErrorLevel)) 54 55 lvlEnabler.SetLevel(zapcore.ErrorLevel) 56 require.False(t, cc.Enabled(zapcore.DebugLevel)) 57 require.False(t, cc.Enabled(zapcore.InfoLevel)) 58 require.False(t, cc.Enabled(zapcore.WarnLevel)) 59 require.True(t, cc.Enabled(zapcore.ErrorLevel)) 60 61 lvlEnabler.SetLevel(zapcore.DebugLevel) 62 63 core := cc.With([]zap.Field{zap.String("key", "value")}) 64 require.NotNil(t, core) 65 66 ent := cc.Check(zapcore.Entry{Level: zapcore.DebugLevel}, nil) 67 err := cc.Write(ent.Entry, []zap.Field{zap.String("key", "value")}) 68 require.NoError(t, err) 69 _ = cc.Sync() 70 71 cc, err = WrapCore(cc, componentCoreEncoderCfg()) 72 require.NoError(t, err) 73 require.NotNil(t, cc) 74 err = cc.Write(zapcore.Entry{Level: zapcore.DebugLevel, LoggerName: "commonCore"}, []zap.Field{zap.String("key", "value")}) 75 require.NoError(t, err) 76 _ = cc.Sync() 77 }