-
Notifications
You must be signed in to change notification settings - Fork 3
/
logger.go
66 lines (59 loc) · 2.05 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
package zapKit
import (
"github.com/richelieu-yang/chimera/v2/src/core/errorKit"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"io"
)
// NewLogger
/*
@param writer 可以是: ioKit.NewRotatableWriteCloser()
@param level e.g. zap.InfoLevel
*/
func NewLogger(writer io.Writer, level zapcore.Level) (*zap.Logger, error) {
if writer == nil {
return nil, errorKit.New("writer == nil")
}
encoder := getEncoder()
writeSyncer := zapcore.AddSync(writer)
atomicLevel := zap.NewAtomicLevel()
atomicLevel.SetLevel(level)
core := zapcore.NewCore(encoder, writeSyncer, atomicLevel)
return zap.New(core, zap.AddCaller()), nil
}
func getEncoder() zapcore.Encoder {
encoderConfig := zap.NewProductionEncoderConfig()
encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
return zapcore.NewConsoleEncoder(encoderConfig)
}
//// NewLogger1
///*
//@param level e.g. zap.InfoLevel
//*/
//func NewLogger1(logPath string, maxFileSize, maxFileIndex int, compress bool, level zapcore.Level) (*zap.Logger, error) {
// // 由于调用输出时才会尝试生成日志文件(包括创建父目录),失败则会在控制台有错误输出:
// // e.g. 2022-12-07 11:03:01.742597 +0800 CST m=+0.000902876 write error: can't make directories for new logfile: mkdir /logs: read-only file system
// // 因此,还不如在初始化logger时先把该做的都做了.
// if err := fileKit.MkParentDirs(logPath); err != nil {
// return nil, err
// }
//
// encoder := getEncoder()
// writeSyncer := getLogWriter(logPath, maxFileSize, maxFileIndex, compress)
//
// atomicLevel := zap.NewAtomicLevel()
// atomicLevel.SetLevel(level)
//
// core := zapcore.NewCore(encoder, writeSyncer, atomicLevel)
// return zap.New(core, zap.AddCaller()), nil
//}
//func getLogWriter(logPath string, maxFileSize, maxFileIndex int, compress bool) zapcore.WriteSyncer {
// lumberJackLogger := &lumberjack.Logger{
// Filename: logPath,
// MaxSize: maxFileSize,
// MaxBackups: maxFileIndex,
// Compress: compress,
// }
// return zapcore.AddSync(lumberJackLogger)
//}