This repository has been archived by the owner on Dec 8, 2020. It is now read-only.
forked from shenghui0779/yiigo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
116 lines (87 loc) · 1.94 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
package yiigo
import (
"sync"
"time"
"github.com/pelletier/go-toml"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gopkg.in/natefinch/lumberjack.v2"
)
var (
logger *zap.Logger
logMap sync.Map
)
type logConfig struct {
Path string `toml:"path"`
MaxSize int `toml:"max_size"`
MaxBackups int `toml:"max_backups"`
MaxAge int `toml:"max_age"`
Compress bool `toml:"compress"`
}
// newLogger returns a new logger.
func newLogger(cfg *logConfig, debug bool) *zap.Logger {
if debug {
cfg := zap.NewDevelopmentConfig()
cfg.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
cfg.EncoderConfig.EncodeTime = MyTimeEncoder
l, _ := cfg.Build()
return l
}
w := zapcore.AddSync(&lumberjack.Logger{
Filename: cfg.Path,
MaxSize: cfg.MaxSize,
MaxBackups: cfg.MaxBackups,
MaxAge: cfg.MaxAge,
Compress: cfg.Compress,
})
c := zap.NewProductionEncoderConfig()
c.TimeKey = "time"
c.EncodeTime = MyTimeEncoder
c.EncodeCaller = zapcore.FullCallerEncoder
core := zapcore.NewCore(zapcore.NewJSONEncoder(c), w, zap.DebugLevel)
return zap.New(core, zap.AddCaller())
}
func initLogger(debug bool) {
tree, ok := env.get("log").(*toml.Tree)
if !ok {
return
}
keys := tree.Keys()
if len(keys) == 0 {
return
}
for _, v := range keys {
node, ok := tree.Get(v).(*toml.Tree)
if !ok {
continue
}
cfg := &logConfig{
Path: "app.log",
MaxSize: 500,
MaxBackups: 0,
MaxAge: 0,
Compress: true,
}
node.Unmarshal(cfg)
l := newLogger(cfg, debug)
if v == AsDefault {
logger = l
}
logMap.Store(v, l)
}
}
// Logger returns a logger
func Logger(name ...string) *zap.Logger {
if len(name) == 0 {
return logger
}
v, ok := logMap.Load(name[0])
if !ok {
return logger
}
return v.(*zap.Logger)
}
// MyTimeEncoder zap time encoder.
func MyTimeEncoder(t time.Time, e zapcore.PrimitiveArrayEncoder) {
e.AppendString(t.Format("2006-01-02 15:04:05"))
}