/
logger.go
246 lines (205 loc) · 5.52 KB
/
logger.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
package logger
import (
"io"
"os"
"path/filepath"
"time"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gopkg.in/natefinch/lumberjack.v2"
)
const (
// DefaultLevel the default log level
DefaultLevel = zapcore.InfoLevel
// DefaultTimeLayout the default time layout;
DefaultTimeLayout = time.RFC3339
)
// Option custom setup config
type Option func(*option)
type option struct {
level zapcore.Level
fields map[string]string
file io.Writer
timeLayout string
disableConsole bool
}
// WithDebugLevel only greater than 'level' will output
func WithDebugLevel() Option {
return func(opt *option) {
opt.level = zapcore.DebugLevel
}
}
// WithInfoLevel only greater than 'level' will output
func WithInfoLevel() Option {
return func(opt *option) {
opt.level = zapcore.InfoLevel
}
}
// WithWarnLevel only greater than 'level' will output
func WithWarnLevel() Option {
return func(opt *option) {
opt.level = zapcore.WarnLevel
}
}
// WithErrorLevel only greater than 'level' will output
func WithErrorLevel() Option {
return func(opt *option) {
opt.level = zapcore.ErrorLevel
}
}
// WithField add some field(s) to log
func WithField(key, value string) Option {
return func(opt *option) {
opt.fields[key] = value
}
}
// WithFileP write log to some file
func WithFileP(file string) Option {
dir := filepath.Dir(file)
if err := os.MkdirAll(dir, 0766); err != nil {
panic(err)
}
f, err := os.OpenFile(file, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0766)
if err != nil {
panic(err)
}
return func(opt *option) {
opt.file = zapcore.Lock(f)
}
}
// WithFileRotationP write log to some file with rotation
func WithFileRotationP(file string) Option {
dir := filepath.Dir(file)
if err := os.MkdirAll(dir, 0766); err != nil {
panic(err)
}
return func(opt *option) {
opt.file = &lumberjack.Logger{ // concurrent-safed
Filename: file, // 文件路径
MaxSize: 128, // 单个文件最大尺寸,默认单位 M
MaxBackups: 300, // 最多保留 300 个备份
MaxAge: 30, // 最大时间,默认单位 day
LocalTime: true, // 使用本地时间
Compress: true, // 是否压缩 disabled by default
}
}
}
// WithTimeLayout custom time format
func WithTimeLayout(timeLayout string) Option {
return func(opt *option) {
opt.timeLayout = timeLayout
}
}
// WithDisableConsole WithEnableConsole write log to os.Stdout or os.Stderr
func WithDisableConsole() Option {
return func(opt *option) {
opt.disableConsole = true
}
}
// NewJSONLogger return a json-encoder zap logger,
func NewJSONLogger(opts ...Option) (*zap.Logger, error) {
opt := &option{level: DefaultLevel, fields: make(map[string]string)}
for _, f := range opts {
f(opt)
}
timeLayout := DefaultTimeLayout
if opt.timeLayout != "" {
timeLayout = opt.timeLayout
}
// similar to zap.NewProductionEncoderConfig()
encoderConfig := zapcore.EncoderConfig{
TimeKey: "time",
LevelKey: "level",
NameKey: "logger", // used by logger.Named(key); optional; useless
CallerKey: "caller",
MessageKey: "msg",
StacktraceKey: "stacktrace", // use by zap.AddStacktrace; optional; useless
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: zapcore.LowercaseLevelEncoder, // 小写编码器
EncodeTime: func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(t.Format(timeLayout))
},
EncodeDuration: zapcore.MillisDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder, // 全路径编码器
}
jsonEncoder := zapcore.NewJSONEncoder(encoderConfig)
// lowPriority usd by info\debug\warn
lowPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl >= opt.level && lvl < zapcore.ErrorLevel
})
// highPriority usd by error\panic\fatal
highPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl >= opt.level && lvl >= zapcore.ErrorLevel
})
stdout := zapcore.Lock(os.Stdout) // lock for concurrent safe
stderr := zapcore.Lock(os.Stderr) // lock for concurrent safe
core := zapcore.NewTee()
if !opt.disableConsole {
core = zapcore.NewTee(
zapcore.NewCore(jsonEncoder,
zapcore.NewMultiWriteSyncer(stdout),
lowPriority,
),
zapcore.NewCore(jsonEncoder,
zapcore.NewMultiWriteSyncer(stderr),
highPriority,
),
)
}
if opt.file != nil {
core = zapcore.NewTee(core,
zapcore.NewCore(jsonEncoder,
zapcore.AddSync(opt.file),
zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl >= opt.level
}),
),
)
}
logger := zap.New(core,
zap.AddCaller(),
zap.ErrorOutput(stderr),
)
for key, value := range opt.fields {
logger = logger.WithOptions(zap.Fields(zapcore.Field{Key: key, Type: zapcore.StringType, String: value}))
}
return logger, nil
}
var _ Meta = (*meta)(nil)
// Meta key-value
type Meta interface {
Key() string
Value() interface{}
meta()
}
type meta struct {
key string
value interface{}
}
func (m *meta) Key() string {
return m.key
}
func (m *meta) Value() interface{} {
return m.value
}
func (m *meta) meta() {}
// NewMeta create meat
func NewMeta(key string, value interface{}) Meta {
return &meta{key: key, value: value}
}
// WrapMeta wrap meta to zap fields
func WrapMeta(err error, metas ...Meta) (fields []zap.Field) {
capacity := len(metas) + 1 // namespace meta
if err != nil {
capacity++
}
fields = make([]zap.Field, 0, capacity)
if err != nil {
fields = append(fields, zap.Error(err))
}
fields = append(fields, zap.Namespace("meta"))
for _, meta := range metas {
fields = append(fields, zap.Any(meta.Key(), meta.Value()))
}
return
}