-
Notifications
You must be signed in to change notification settings - Fork 3
/
log.go
62 lines (53 loc) · 1.33 KB
/
log.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
package main
import (
"errors"
"os"
"strings"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// NewLogger : new a `zap loger` with some options
func NewLogger(filepath string, level string, fmt string) (logger *zap.Logger, err error) {
level = strings.ToLower(level)
fmt = strings.ToLower(fmt)
var zapLevel zapcore.Level
switch level {
case "debug":
zapLevel = zapcore.DebugLevel
case "info":
zapLevel = zapcore.InfoLevel
case "warning":
zapLevel = zapcore.WarnLevel
default:
return nil, errors.New("unsupported log level: " + level)
}
var zapEncoder zapcore.Encoder
encConfig := getEncoderConfig()
switch fmt {
case "plain":
zapEncoder = zapcore.NewConsoleEncoder(encConfig)
case "json":
zapEncoder = zapcore.NewJSONEncoder(encConfig)
default:
return nil, errors.New("unsupported log format: " + fmt)
}
var file *os.File
if filepath == "" {
file = os.Stderr
} else {
file, err = os.OpenFile(filepath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
return nil, err
}
}
fileSync := zapcore.AddSync(file)
core := zapcore.NewCore(zapEncoder, fileSync, zapLevel)
logger = zap.New(core)
return logger, nil
}
func getEncoderConfig() zapcore.EncoderConfig {
e := zap.NewProductionEncoderConfig()
e.EncodeLevel = zapcore.CapitalLevelEncoder
e.EncodeTime = zapcore.ISO8601TimeEncoder
return e
}