github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/zlog/example_test.go (about) 1 package zlog 2 3 import ( 4 "context" 5 "os" 6 7 "go.uber.org/zap" 8 "go.uber.org/zap/zapcore" 9 ) 10 11 func testHelperReplaceGlobalsToStdout(ctxFunc func(ctx context.Context) CtxResult) func() { 12 cfg := &Config{ 13 Level: "trace", 14 Format: "json", 15 DisableTimestamp: true, 16 DisableCaller: true, 17 DisableStacktrace: true, 18 GlobalConfig: GlobalConfig{ 19 CtxHandler: CtxHandler{ 20 WithCtx: ctxFunc, 21 }, 22 }, 23 } 24 l, p, err := NewWithOutput(cfg, zapcore.AddSync(os.Stdout)) 25 if err != nil { 26 panic(err) 27 } 28 return ReplaceGlobals(l, p) 29 } 30 31 func ExampleWith() { 32 defer testHelperReplaceGlobalsToStdout(nil)() 33 34 With(zap.String("k1", "v1"), zap.Int64("k2", 54321)). 35 Info("example with") 36 37 // Output: 38 // {"level":"info","msg":"example with","k1":"v1","k2":54321} 39 } 40 41 func ExampleWithCtx() { 42 43 demoCtxFunc := func(ctx context.Context) CtxResult { 44 return CtxResult{ 45 Fields: []zap.Field{zap.String("ctx1", "v1"), zap.Int64("ctx2", 123)}, 46 } 47 } 48 defer testHelperReplaceGlobalsToStdout(demoCtxFunc)() 49 50 logger := WithCtx(context.Background(), 51 zap.String("k3", "v3"), // add a new field 52 zap.String("ctx2", "override"), // override "ctx2" from context 53 ) 54 logger.Info("example with ctx") 55 56 // Output: 57 // {"level":"info","msg":"example with ctx","ctx1":"v1","ctx2":"override","k3":"v3"} 58 } 59 60 func ExampleAddFields() { 61 defer testHelperReplaceGlobalsToStdout(nil)() 62 63 ctx := context.Background() 64 ctx = AddFields(ctx, 65 zap.String("ctx1", "v1"), 66 zap.Int64("ctx2", 123)) 67 ctx = AddFields(ctx, 68 zap.String("k3", "v3"), // add a new field 69 zap.String("ctx2", "override"), // override "ctx2" 70 ) 71 logger := WithCtx(ctx) 72 logger.Info("example AddFields") 73 74 // Output: 75 // {"level":"info","msg":"example AddFields","ctx1":"v1","ctx2":"override","k3":"v3"} 76 }