github.com/aaabigfish/gopkg@v1.1.0/log/option.go (about) 1 package log 2 3 import ( 4 "os" 5 6 "go.uber.org/zap" 7 "go.uber.org/zap/zapcore" 8 ) 9 10 type Option interface { 11 apply(cfg *conf) 12 } 13 14 type ExtraKey string 15 16 type option func(cfg *conf) 17 18 func (fn option) apply(cfg *conf) { 19 fn(cfg) 20 } 21 22 type CoreConfig struct { 23 Enc zapcore.Encoder 24 Ws zapcore.WriteSyncer 25 Lvl zapcore.LevelEnabler 26 } 27 28 type conf struct { 29 extraKeys []ExtraKey 30 coreConfigs []CoreConfig 31 zapOpts []zap.Option 32 } 33 34 // defaultCoreConfig default zapcore config: json encoder, atomic level, stdout write syncer 35 func defaultCoreConfig() *CoreConfig { 36 // default log encoder 37 enc := zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()) 38 // default log level 39 lvl := zap.NewAtomicLevelAt(zap.InfoLevel) 40 // default write syncer stdout 41 ws := zapcore.AddSync(os.Stdout) 42 43 return &CoreConfig{ 44 Enc: enc, 45 Ws: ws, 46 Lvl: lvl, 47 } 48 } 49 50 // defaultConfig default config 51 func defaultConfig() *conf { 52 return &conf{ 53 coreConfigs: []CoreConfig{*defaultCoreConfig()}, 54 zapOpts: []zap.Option{}, 55 } 56 } 57 58 // WithCoreEnc zapcore encoder 59 func WithCoreEnc(enc zapcore.Encoder) Option { 60 return option(func(cfg *conf) { 61 cfg.coreConfigs[0].Enc = enc 62 }) 63 } 64 65 // WithCoreWs zapcore write syncer 66 func WithCoreWs(ws zapcore.WriteSyncer) Option { 67 return option(func(cfg *conf) { 68 cfg.coreConfigs[0].Ws = ws 69 }) 70 } 71 72 // WithCoreLevel zapcore log level 73 func WithCoreLevel(lvl zap.AtomicLevel) Option { 74 return option(func(cfg *conf) { 75 cfg.coreConfigs[0].Lvl = lvl 76 }) 77 } 78 79 // WithCores zapcore 80 func WithCores(coreConfigs ...CoreConfig) Option { 81 return option(func(cfg *conf) { 82 cfg.coreConfigs = coreConfigs 83 }) 84 } 85 86 // WithZapOptions add origin zap option 87 func WithZapOptions(opts ...zap.Option) Option { 88 return option(func(cfg *conf) { 89 cfg.zapOpts = append(cfg.zapOpts, opts...) 90 }) 91 } 92 93 // WithExtraKeys allow you log extra values from context 94 func WithExtraKeys(keys []ExtraKey) Option { 95 return option(func(cfg *conf) { 96 for _, k := range keys { 97 if !inArray(k, cfg.extraKeys) { 98 cfg.extraKeys = append(cfg.extraKeys, k) 99 } 100 } 101 }) 102 } 103 104 // inArray check if a string in a slice 105 func inArray(key ExtraKey, arr []ExtraKey) bool { 106 for _, k := range arr { 107 if k == key { 108 return true 109 } 110 } 111 return false 112 }