/
logger.go
96 lines (82 loc) · 1.69 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
package logger
import (
"fmt"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"os"
"strings"
)
const (
envLogLevel = "LOG_LEVEL"
envLogOutput = "LOG_OUTPUT"
)
var (
log logger
)
type bookstoreLogger interface {
Print(v ...interface{})
Printf(format string, v ...interface{})
}
type logger struct {
log *zap.Logger
}
func init() {
logConfig := zap.Config{
OutputPaths: []string{getOutput()},
Level: zap.NewAtomicLevelAt(getLevel()),
Encoding: "json",
EncoderConfig: zapcore.EncoderConfig{
LevelKey: "level",
TimeKey: "time",
MessageKey: "msg",
EncodeTime: zapcore.ISO8601TimeEncoder,
EncodeLevel: zapcore.LowercaseLevelEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
},
}
var err error
if log.log, err = logConfig.Build(); err != nil {
panic(err)
}
}
func getLevel() zapcore.Level {
switch strings.ToLower(strings.TrimSpace(os.Getenv(envLogLevel))) {
case "debug":
return zap.DebugLevel
case "info":
return zap.InfoLevel
case "error":
return zap.ErrorLevel
default:
return zap.InfoLevel
}
}
func getOutput() string {
output := strings.TrimSpace(os.Getenv(envLogOutput))
if output == "" {
return "stdout"
}
return output
}
func GetLogger() bookstoreLogger {
return log
}
func (l logger) Printf(format string, v ...interface{}) {
if len(v) == 0 {
Info(format)
} else {
Info(fmt.Sprintf(format, v...))
}
}
func (l logger) Print(v ...interface{}) {
Info(fmt.Sprintf("%v", v))
}
func Info(msg string, tags ...zap.Field) {
log.log.Info(msg, tags...)
log.log.Sync()
}
func Error(msg string, err error, tags ...zap.Field) {
tags = append(tags, zap.NamedError("error", err))
log.log.Error(msg, tags...)
log.log.Sync()
}