/
logger.go
103 lines (84 loc) · 1.94 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
103
// SPDX-License-Identifier: Apache-2.0
// Copyright 2021 Authors of KubeArmor
package log
import (
"encoding/json"
"time"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// ============ //
// == Logger == //
// ============ //
// zapLogger Handler
var zapLogger *zap.SugaredLogger
// init Function
func init() {
initLogger()
}
// customTimeEncoder Function
func customTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(t.Format("2006-01-02 15:04:05.000000"))
}
// initLogger Function
func initLogger() {
defaultConfig := []byte(`{
"level": "debug",
"encoding": "console",
"outputPaths": ["stdout"],
"encoderConfig": {
"messageKey": "message",
"levelKey": "level",
"nameKey": "logger",
"timeKey": "time",
"callerKey": "logger",
"stacktraceKey": "stacktrace",
"callstackKey": "callstack",
"errorKey": "error",
"levelEncoder": "capitalColor",
"durationEncoder": "second",
"sampling": {
"initial": "3",
"thereafter": "10"
}
}
}`)
config := zap.Config{}
if err := json.Unmarshal(defaultConfig, &config); err != nil {
panic(err)
}
config.EncoderConfig.EncodeTime = customTimeEncoder
config.Level.SetLevel(zap.DebugLevel) // if we need to set log level
logger, err := config.Build()
if err != nil {
panic(err)
}
zapLogger = logger.Sugar()
}
// ======================= //
// == Logging Functions == //
// ======================= //
// Print Function
func Print(message string) {
zapLogger.Info(message)
}
// Printf Function
func Printf(message string, args ...interface{}) {
zapLogger.Infof(message, args...)
}
// Debug Function
func Debug(message string) {
zapLogger.Debug(message)
}
// Debugf Function
func Debugf(message string, args ...interface{}) {
zapLogger.Debugf(message, args...)
}
// Err Function
func Err(message string) {
zapLogger.Error(message)
}
// Errf Function
func Errf(message string, args ...interface{}) {
zapLogger.Errorf(message, args...)
}