-
Notifications
You must be signed in to change notification settings - Fork 0
/
setup.go
103 lines (90 loc) · 2.78 KB
/
setup.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
package logx
import (
"io"
"os"
"strings"
"github.com/robfig/cron/v3"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gopkg.in/natefinch/lumberjack.v2"
)
var (
// levelController 日志输出基本控制器
levelController = zap.NewAtomicLevelAt(zap.DebugLevel)
// DefaultConfig 日志配置
DefaultConfig = zapcore.EncoderConfig{
CallerKey: "line",
LevelKey: "level",
MessageKey: "message",
TimeKey: "time",
StacktraceKey: "stacktrace",
LineEnding: zapcore.DefaultLineEnding,
EncodeTime: zapcore.ISO8601TimeEncoder,
EncodeLevel: func(level zapcore.Level, encoder zapcore.PrimitiveArrayEncoder) {
encoder.AppendString(firstUpper(level.String()))
},
EncodeCaller: func(caller zapcore.EntryCaller, encoder zapcore.PrimitiveArrayEncoder) {
encoder.AppendString("[" + caller.TrimmedPath() + "]")
},
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeName: zapcore.FullNameEncoder,
ConsoleSeparator: " ",
}
)
// initDefaultLogger 在没有外部调用Setup进行日志库设置的情况下,进行默认的日志库配置;
// 以便开发单独的小应用的使用时候;
func initDefaultLogger() {
SetupConsoleLogger("", zap.AddStacktrace(zapcore.ErrorLevel))
}
// CloseLogger 系统运行结束时,将日志落盘;
func CloseLogger() {
_ = rootLogger.Sync()
}
// SetupConsoleLogger 配置日志记录器
func SetupConsoleLogger(logfile string, options ...zap.Option) {
encoder := zapcore.NewConsoleEncoder(DefaultConfig)
SetupLogger(logfile, encoder, options...)
}
// SetupJSONLogger 配置日志记录器
func SetupJSONLogger(logfile string, options ...zap.Option) {
encoder := zapcore.NewJSONEncoder(DefaultConfig)
SetupLogger(logfile, encoder, options...)
}
func SetupLogger(logfile string, encoder zapcore.Encoder, options ...zap.Option) {
// 将日志输出到屏幕
core := zapcore.NewCore(encoder, os.Stdout, levelController)
// 将日志输出到滚动切割文件中
if logfile != "" {
lumberWriterSync := zapcore.AddSync(fileWriter(logfile))
core = zapcore.NewCore(encoder, lumberWriterSync, levelController)
}
options = append(options, zap.AddCaller(), zap.AddCallerSkip(2))
// 生产根logger,设置输出调度点(上跳2行)
_zLogger := zap.New(core, options...)
rootLogger = newzLogger(_zLogger)
}
func firstUpper(s string) string {
if s == "" {
return ""
}
return strings.ToUpper(s[:1]) + s[1:]
}
func SetLevel(l zapcore.Level) {
levelController.SetLevel(l)
}
func fileWriter(path string) io.Writer {
out := &lumberjack.Logger{
Filename: path,
MaxBackups: 7,
MaxSize: 50,
MaxAge: 7,
Compress: false, // disabled by default
LocalTime: true, // use local time zone
}
c := cron.New()
_, _ = c.AddFunc("59 23 * * *", func() {
_ = out.Rotate()
})
c.Start()
return out
}