/
config.go
212 lines (183 loc) · 6.96 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package log_config
import (
"encoding/json"
"fmt"
"github.com/pubgo/lava/internal/pkg/utils"
"os"
"path/filepath"
"github.com/pubgo/xerror"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
lumberjack "gopkg.in/natefinch/lumberjack.v2"
)
var (
allLevels = []zapcore.Level{zapcore.DebugLevel, zapcore.InfoLevel, zapcore.WarnLevel, zapcore.ErrorLevel, zapcore.FatalLevel}
)
func GlobalLevel(l ...zapcore.Level) string {
if globalLevel == nil {
return ""
}
if len(l) > 0 {
return globalLevel.String()
}
globalLevel.SetLevel(l[0])
return l[0].String()
}
var globalLevel *zap.AtomicLevel
type option func(opts *Config)
type encoderConfig struct {
MessageKey string `json:"messageKey" yaml:"messageKey" toml:"messageKey"`
LevelKey string `json:"levelKey" yaml:"levelKey" toml:"levelKey"`
TimeKey string `json:"timeKey" yaml:"timeKey" toml:"timeKey"`
NameKey string `json:"nameKey" yaml:"nameKey" toml:"nameKey"`
CallerKey string `json:"callerKey" yaml:"callerKey" toml:"callerKey"`
StacktraceKey string `json:"stacktraceKey" yaml:"stacktraceKey" toml:"stacktraceKey"`
LineEnding string `json:"lineEnding" yaml:"lineEnding" toml:"lineEnding"`
EncodeLevel string `json:"levelEncoder" yaml:"levelEncoder" toml:"levelEncoder"`
EncodeTime string `json:"timeEncoder" yaml:"timeEncoder" toml:"timeEncoder"`
EncodeDuration string `json:"durationEncoder" yaml:"durationEncoder" toml:"durationEncoder"`
EncodeCaller string `json:"callerEncoder" yaml:"callerEncoder" toml:"callerEncoder"`
EncodeName string `json:"nameEncoder" yaml:"nameEncoder" toml:"nameEncoder"`
ConsoleSeparator string `json:"consoleSeparator" yaml:"consoleSeparator"`
}
type samplingConfig struct {
Initial int `json:"initial" yaml:"initial" toml:"initial"`
Thereafter int `json:"thereafter" yaml:"thereafter" toml:"thereafter"`
}
type rotateCfg struct {
Filename string `json:"filename" yaml:"filename"`
MaxSize int `json:"maxsize" yaml:"maxsize"`
MaxAge int `json:"maxage" yaml:"maxage"`
MaxBackups int `json:"maxbackups" yaml:"maxbackups"`
LocalTime bool `json:"localtime" yaml:"localtime"`
Compress bool `json:"compress" yaml:"compress"`
}
type Config struct {
Level string `json:"level" yaml:"level" toml:"level"`
Development bool `json:"development" yaml:"development" toml:"development"`
DisableCaller bool `json:"disableCaller" yaml:"disableCaller" toml:"disableCaller"`
DisableStacktrace bool `json:"disableStacktrace" yaml:"disableStacktrace" toml:"disableStacktrace"`
Sampling *samplingConfig `json:"sampling" yaml:"sampling" toml:"sampling"`
Encoding string `json:"encoding" yaml:"encoding" toml:"encoding"`
EncoderConfig encoderConfig `json:"encoderConfig" yaml:"encoderConfig" toml:"encoderConfig"`
OutputPaths []string `json:"outputPaths" yaml:"outputPaths" toml:"outputPaths"`
ErrorOutputPaths []string `json:"errorOutputPaths" yaml:"errorOutputPaths" toml:"errorOutputPaths"`
InitialFields map[string]interface{} `json:"initialFields" yaml:"initialFields" toml:"initialFields"`
Rotate *rotateCfg `json:"rotate" yaml:"rotate"`
SamplingHook func(zapcore.Entry) `json:"-" yaml:"-"`
}
func (t Config) handleOpts(opts ...option) Config {
for _, opt := range opts {
opt(&t)
}
return t
}
func (t Config) Build(name string, opts ...zap.Option) (_ *zap.Logger) {
zapCfg := zap.Config{}
var dt = xerror.PanicBytes(json.Marshal(&t))
xerror.Panic(json.Unmarshal(dt, &zapCfg))
// 保留全局log level, 用于后期动态修改
globalLevel = &zapCfg.Level
key := utils.FirstNotEmpty(t.EncoderConfig.EncodeLevel, defaultKey)
zapCfg.EncoderConfig.EncodeLevel = levelEncoder[key]
key = utils.FirstNotEmpty(t.EncoderConfig.EncodeTime, defaultKey)
zapCfg.EncoderConfig.EncodeTime = zapcore.TimeEncoderOfLayout(key)
if encoder, ok := timeEncoder[key]; ok {
zapCfg.EncoderConfig.EncodeTime = encoder
}
key = utils.FirstNotEmpty(t.EncoderConfig.EncodeDuration, defaultKey)
zapCfg.EncoderConfig.EncodeDuration = durationEncoder[key]
key = utils.FirstNotEmpty(t.EncoderConfig.EncodeCaller, defaultKey)
zapCfg.EncoderConfig.EncodeCaller = callerEncoder[key]
key = utils.FirstNotEmpty(t.EncoderConfig.EncodeName, defaultKey)
zapCfg.EncoderConfig.EncodeName = nameEncoder[key]
// 采样hook设置
if t.SamplingHook != nil {
zapCfg.Sampling.Hook = func(entry zapcore.Entry, decision zapcore.SamplingDecision) {
if decision == zapcore.LogDropped {
return
}
t.SamplingHook(entry)
}
}
var log = xerror.PanicErr(zapCfg.Build(opts...)).(*zap.Logger)
if t.Rotate != nil {
var cores []zapcore.Core
for i := range allLevels {
lvl := allLevels[i]
var w = &lumberjack.Logger{
Filename: os.ExpandEnv(filepath.Join(t.Rotate.Filename, lvl.String(), fmt.Sprintf("%s.log", name))),
MaxSize: t.Rotate.MaxSize,
MaxBackups: t.Rotate.MaxBackups,
MaxAge: t.Rotate.MaxAge,
Compress: t.Rotate.Compress,
}
var cfg = zapCfg.EncoderConfig
cfg.EncodeLevel = zapcore.LowercaseLevelEncoder
cores = append(cores, zapcore.NewCore(
zapcore.NewJSONEncoder(cfg), zapcore.AddSync(w),
zap.LevelEnablerFunc(func(level zapcore.Level) bool { return level == lvl })))
}
log = log.WithOptions(zap.WrapCore(func(core zapcore.Core) zapcore.Core { return zapcore.NewTee(append(cores, core)...) }))
}
return log
}
func NewDevConfig(opts ...option) Config {
cfg := Config{
Level: "debug",
Development: true,
Encoding: "console",
DisableStacktrace: true,
Rotate: &rotateCfg{
Filename: "${cfg_dir}/logs",
MaxSize: 10,
MaxBackups: 3,
MaxAge: 28,
Compress: false,
},
EncoderConfig: encoderConfig{
TimeKey: "T",
LevelKey: "L",
NameKey: "N",
CallerKey: "C",
MessageKey: "M",
StacktraceKey: "S",
EncodeLevel: "capitalColor",
EncodeTime: "iso8601",
EncodeDuration: "string",
EncodeCaller: "full",
LineEnding: zapcore.DefaultLineEnding,
},
OutputPaths: []string{"stderr"},
ErrorOutputPaths: []string{"stderr"},
}
return cfg.handleOpts(opts...)
}
func NewProdConfig(opts ...option) Config {
cfg := Config{
Level: "info",
Development: false,
Sampling: &samplingConfig{
Initial: 100,
Thereafter: 100,
},
Encoding: "json",
DisableStacktrace: true,
EncoderConfig: encoderConfig{
TimeKey: "ts",
LevelKey: "level",
NameKey: "logger",
CallerKey: "caller",
MessageKey: "msg",
StacktraceKey: "stacktrace",
EncodeLevel: "default",
EncodeTime: "default",
EncodeDuration: "default",
EncodeCaller: "default",
LineEnding: zapcore.DefaultLineEnding,
},
OutputPaths: []string{"stderr"},
ErrorOutputPaths: []string{"stderr"},
}
return cfg.handleOpts(opts...)
}