This repository has been archived by the owner on Jan 28, 2022. It is now read-only.
/
logger.go
102 lines (92 loc) · 2.45 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
97
98
99
100
101
102
// Created from https://github.com/nkmr-jp/go-logger-scaffold
package logger
import (
"log"
"os"
"os/exec"
"strings"
"sync"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
var (
once sync.Once
zapLogger *zap.Logger
consoleType ConsoleType
outputType OutputType
version string
logLevel zapcore.Level // Default is InfoLevel
callerEncoder zapcore.CallerEncoder
consoleFields []string
)
// Initialize the Logger.
// Outputs short logs to the console and Write structured and detailed json logs to the log file.
func InitLogger() *zap.Logger {
once.Do(func() {
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
initZapLogger()
Info("INIT_LOGGER")
})
return zapLogger
}
// See https://pkg.go.dev/go.uber.org/zap
func initZapLogger() {
log.Printf("log level: %v", logLevel.CapitalString())
log.Printf("output type: %v", outputType.String())
encoderConfig := zapcore.EncoderConfig{
TimeKey: "ts",
LevelKey: "level",
NameKey: "name",
CallerKey: "caller",
MessageKey: "msg",
StacktraceKey: "stacktrace",
FunctionKey: "function",
EncodeLevel: zapcore.CapitalLevelEncoder,
EncodeTime: zapcore.RFC3339NanoTimeEncoder,
EncodeDuration: zapcore.StringDurationEncoder,
EncodeCaller: getCallerEncoder(),
}
core := zapcore.NewCore(
zapcore.NewJSONEncoder(encoderConfig),
zapcore.NewMultiWriteSyncer(getSyncers()...),
logLevel,
)
zapLogger = zap.New(core, zap.AddCaller(), zap.AddStacktrace(zapcore.ErrorLevel)).With(
zap.String("version", getVersion()),
zap.String("hostname", *getHost()),
)
}
func getVersion() string {
if version != "" {
return version
}
if out, err := exec.Command("git", "rev-parse", "--short", "HEAD").Output(); err == nil {
return strings.TrimRight(string(out), "\n")
}
return "undefined"
}
func getHost() *string {
ret, err := os.Hostname()
if err != nil {
log.Print(err)
return nil
}
return &ret
}
func getCallerEncoder() zapcore.CallerEncoder {
if callerEncoder != nil {
return callerEncoder
}
return zapcore.ShortCallerEncoder
}
func getSyncers() (syncers []zapcore.WriteSyncer) {
switch outputType {
case OutputTypeShortConsoleAndFile, OutputTypeFile:
syncers = append(syncers, zapcore.AddSync(newRotateLogs()))
case OutputTypeConsoleAndFile:
syncers = append(syncers, zapcore.AddSync(os.Stdout), zapcore.AddSync(newRotateLogs()))
case OutputTypeConsole:
syncers = append(syncers, zapcore.AddSync(os.Stdout))
}
return
}