/
zap.go
77 lines (62 loc) · 1.48 KB
/
zap.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
package log
import (
"os"
"github.com/spf13/viper"
"go.uber.org/fx"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gopkg.in/natefinch/lumberjack.v2"
)
// Options is log configuration struct
type Options struct {
Filename string
MaxSize int
MaxBackups int
MaxAge int
Level string
Stdout bool
}
func NewOptions(v *viper.Viper) (*Options, error) {
var (
err error
o = &Options{}
)
if err = v.UnmarshalKey("log", o); err != nil {
return nil, err
}
return o, err
}
// NewLogger for init zap log library
func NewLogger(o *Options) (*zap.Logger, error) {
var (
err error
level = zap.NewAtomicLevel()
logger *zap.Logger
)
if err = level.UnmarshalText([]byte(o.Level)); err != nil {
return nil, err
}
fw := zapcore.AddSync(&lumberjack.Logger{
Filename: o.Filename,
MaxSize: o.MaxSize, // megabytes
MaxBackups: o.MaxBackups,
MaxAge: o.MaxAge, // days
})
cw := zapcore.Lock(os.Stdout)
// file core 采用jsonEncoder
cores := make([]zapcore.Core, 0, 2)
je := zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig())
cores = append(cores, zapcore.NewCore(je, fw, level))
// stdout core 采用 ConsoleEncoder
if o.Stdout {
ce := zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig())
cores = append(cores, zapcore.NewCore(ce, cw, level))
}
core := zapcore.NewTee(cores...)
logger = zap.New(core)
zap.ReplaceGlobals(logger)
return logger, err
}
func Provide() fx.Option {
return fx.Provide(NewOptions, NewLogger)
}