This repository has been archived by the owner on Jul 8, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
zap.go
85 lines (70 loc) · 1.7 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
78
79
80
81
82
83
84
85
package zapx
import (
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"log"
"strings"
)
type (
// LoggerOptions are options for constructing a Logger
LoggerOptions struct {
Level string
LogJSON bool
Development bool
Stacktrace bool
}
LogLevel string
)
func (l LogLevel) String() string {
return string(l)
}
const (
DebugLevel string = "DEBUG"
InfoLevel string = "INFO"
WarnLevel string = "WARN"
ErrorLevel string = "ERROR"
FatalLevel string = "FATAL"
)
var LogLevelMapping = map[string]zapcore.Level{
DebugLevel: zap.DebugLevel,
InfoLevel: zap.InfoLevel,
WarnLevel: zap.WarnLevel,
ErrorLevel: zap.ErrorLevel,
FatalLevel: zap.FatalLevel,
}
// NewLogger creates a new Logger instance
func NewLogger(options LoggerOptions) (*zap.SugaredLogger, error) {
config := zap.NewDevelopmentConfig()
config.Development = options.Development
config.DisableStacktrace = !options.Stacktrace
if options.LogJSON {
config.Encoding = "json"
} else {
config.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
}
options.Level = strings.ToUpper(options.Level)
if _, exists := LogLevelMapping[options.Level]; !exists {
options.Level = InfoLevel
}
config.Level = zap.NewAtomicLevelAt(LogLevelMapping[options.Level])
logger, err := config.Build()
if err != nil {
log.Fatalf("Failed to enable logger: %s", err)
return nil, err
}
l := logger.Sugar()
l.Debugw("Init Zap Logger.", "LEVEL", config.Level, "LOG_JSON", options.LogJSON)
return l, nil
}
func MustCreateLogger() *zap.SugaredLogger {
logger, err := NewLogger(LoggerOptions{
Level: "DEBUG",
LogJSON: false,
Development: true,
Stacktrace: false,
})
if err != nil {
log.Fatal(err)
}
return logger
}