github.com/zooyer/miskit@v1.0.71/log/log_test.go (about) 1 package log 2 3 import ( 4 "context" 5 "encoding/json" 6 "github.com/zooyer/miskit/trace" 7 "go.uber.org/zap" 8 "go.uber.org/zap/zapcore" 9 "os" 10 "path/filepath" 11 "testing" 12 "time" 13 ) 14 15 func timeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) { 16 enc.AppendString(t.Format("2006-01-02 15:04:05")) 17 } 18 19 func writer(path, name string) (writer zapcore.WriteSyncer, err error) { 20 file, err := os.Create(filepath.Join(path, name)) 21 if err != nil { 22 return 23 } 24 25 return zapcore.AddSync(file), nil 26 } 27 28 func encoder(debug bool) zapcore.Encoder { 29 var config = zap.NewProductionEncoderConfig() 30 if debug { 31 config = zap.NewDevelopmentEncoderConfig() 32 //configs.EncodeLevel = zapcore.CapitalColorLevelEncoder 33 config.EncodeLevel = zapcore.CapitalLevelEncoder 34 } 35 config.EncodeTime = timeEncoder 36 37 //return zapcore.NewMapObjectEncoder() 38 return zapcore.NewConsoleEncoder(config) 39 } 40 41 func TestLog(t *testing.T) { 42 logger := zap.NewExample() 43 logger, _ = zap.NewDevelopment() 44 logger, _ = zap.NewProduction() 45 46 config := zap.NewDevelopmentConfig() 47 config.EncoderConfig = zap.NewDevelopmentEncoderConfig() 48 config.EncoderConfig.EncodeTime = timeEncoder 49 //configs.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder 50 config.EncoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder 51 52 //w, err := writer("./", "test.log") 53 //if err != nil { 54 // t.Fatal(err) 55 //} 56 57 core := zapcore.NewCore(encoder(true), zapcore.AddSync(os.Stdout), zap.DebugLevel) 58 logger = zap.New(core, zap.AddCaller()) 59 defer logger.Sync() 60 61 sugar := logger.Sugar() 62 sugar.Infow("failed to fetch URL", "rpc", "talos", "cost", 32.3, "code", 0) 63 } 64 65 func TestNew(t *testing.T) { 66 var config = Config{ 67 Filename: "", 68 Output: "stdout", 69 Level: "DEBUG", 70 Align: false, 71 Interval: 0, 72 //AutoClear: false, 73 //ClearHours: 0, 74 //Separate: false, 75 } 76 log, err := New(config, TextFormatter(true)) 77 if err != nil { 78 t.Fatal(err) 79 } 80 81 var ctx = context.Background() 82 traceInfo := trace.New(nil, "test") 83 traceInfo.Tag = "test" 84 traceInfo.Lang = "zh-CN" 85 traceInfo.SpanID = "this is span id" 86 traceInfo.Content = json.RawMessage(`{"key": "val"}`) 87 ctx = trace.Set(ctx, traceInfo) 88 89 log.Debug(ctx, "Hello") 90 }