-
Notifications
You must be signed in to change notification settings - Fork 307
/
logger.go
337 lines (295 loc) · 8.99 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
/*
Logger Interface Use instance of logger instead of exported functions
usage example
import (
"errors"
"github.com/rudderlabs/rudder-server/utils/logger"
)
var log logger.LoggerI = &logger.LoggerT{}
or
var log logger.LoggerI = logger.NewLogger()
...
log.Error(...)
*/
//go:generate mockgen -destination=../../mocks/utils/logger/mock_logger.go -package mock_logger github.com/rudderlabs/rudder-server/utils/logger LoggerI
package logger
import (
"bytes"
"errors"
"io"
"net/http"
"runtime"
"strings"
"sync"
"github.com/rudderlabs/rudder-server/config"
"go.uber.org/zap"
)
/*
Using levels(like Debug, Info etc.) in logging is a way to categorize logs based on their importance.
The idea is to have the option of running the application in different logging levels based on
how verbose we want the logging to be.
For example, using Debug level of logging, logs everything and it might slow the application, so we run application
in DEBUG level for local development or when we want to look through the entire flow of events in detail.
We use 4 logging levels here Debug, Info, Error and Fatal.
*/
type LoggerI interface {
IsDebugLevel() bool
Debug(args ...interface{})
Info(args ...interface{})
Warn(args ...interface{})
Error(args ...interface{})
Fatal(args ...interface{})
Debugf(format string, args ...interface{})
Infof(format string, args ...interface{})
Warnf(format string, args ...interface{})
Errorf(format string, args ...interface{})
Fatalf(format string, args ...interface{})
LogRequest(req *http.Request)
Child(s string) LoggerI
}
type LoggerT struct {
name string
parent *LoggerT
}
const (
levelEvent = iota // Logs Event
levelDebug // Most verbose logging level
levelInfo // Logs about state of the application
levelWarn // Logs about warnings
levelError // Logs about errors which dont immediately halt the application
levelFatal // Logs which crashes the application
)
var levelMap = map[string]int{
"EVENT": levelEvent,
"DEBUG": levelDebug,
"INFO": levelInfo,
"WARN": levelWarn,
"ERROR": levelError,
"FATAL": levelFatal,
}
var (
enableConsole bool
enableFile bool
consoleJsonFormat bool
fileJsonFormat bool
rootLevel int
enableTimestamp bool
enableFileNameInLog bool
enableStackTrace bool
logFileLocation string
logFileSize int
)
var (
Log *zap.SugaredLogger
levelConfig map[string]int
loggerLevelsCache map[string]int
levelConfigLock sync.RWMutex
levelConfigStr string
)
func loadConfig() {
rootLevel = levelMap[config.GetEnv("LOG_LEVEL", "INFO")]
config.RegisterBoolConfigVariable(true, &enableConsole, true, "Logger.enableConsole")
config.RegisterBoolConfigVariable(false, &enableFile, true, "Logger.enableFile")
config.RegisterBoolConfigVariable(false, &consoleJsonFormat, true, "Logger.consoleJsonFormat")
config.RegisterBoolConfigVariable(false, &fileJsonFormat, true, "Logger.fileJsonFormat")
config.RegisterStringConfigVariable("/tmp/rudder_log.log", &logFileLocation, true, "Logger.logFileLocation")
config.RegisterIntConfigVariable(100, &logFileSize, true, 1, "Logger.logFileSize")
config.RegisterBoolConfigVariable(true, &enableTimestamp, true, "Logger.enableTimestamp")
config.RegisterBoolConfigVariable(true, &enableFileNameInLog, true, "Logger.enableFileNameInLog")
config.RegisterBoolConfigVariable(false, &enableStackTrace, true, "Logger.enableStackTrace")
// colon separated key value pairs
// Example: "router.GA=DEBUG:warehouse.REDSHIFT=DEBUG"
config.RegisterStringConfigVariable("", &levelConfigStr, false, "Logger.moduleLevels")
levelConfig = make(map[string]int)
levelConfigStr = strings.TrimSpace(levelConfigStr)
if levelConfigStr != "" {
moduleLevelKVs := strings.Split(levelConfigStr, ":")
for _, moduleLevelKV := range moduleLevelKVs {
pair := strings.SplitN(moduleLevelKV, "=", 2)
if len(pair) < 2 {
continue
}
module := strings.TrimSpace(pair[0])
if module == "" {
continue
}
levelStr := strings.TrimSpace(pair[1])
level, ok := levelMap[levelStr]
if !ok {
continue
}
levelConfig[module] = level
}
}
}
var options []zap.Option
func NewLogger() *LoggerT {
return &LoggerT{}
}
// Setup sets up the logger initially
func Init() {
loadConfig()
Log = configureLogger()
loggerLevelsCache = make(map[string]int)
}
func (l *LoggerT) Child(s string) LoggerI {
if s == "" {
return l
}
cp := *l
cp.parent = l
if l.name == "" {
cp.name = s
} else {
cp.name = strings.Join([]string{l.name, s}, ".")
}
return &cp
}
func (l *LoggerT) getLoggingLevel() int {
var found bool
var level int
levelConfigLock.RLock()
if l.name == "" {
level = rootLevel
found = true
}
if !found {
level, found = loggerLevelsCache[l.name]
}
if !found {
level, found = levelConfig[l.name]
}
levelConfigLock.RUnlock()
if found {
return level
}
level = l.parent.getLoggingLevel()
levelConfigLock.Lock()
loggerLevelsCache[l.name] = level
levelConfigLock.Unlock()
return level
}
// SetModuleLevel sets log level for a module and it's children
// Pass empty string for module parameter for resetting root logging level
func SetModuleLevel(module, levelStr string) error {
level, ok := levelMap[levelStr]
if !ok {
return errors.New("invalid level value : " + levelStr)
}
levelConfigLock.Lock()
if module == "" {
rootLevel = level
} else {
levelConfig[module] = level
Log.Info(levelConfig)
}
loggerLevelsCache = make(map[string]int)
levelConfigLock.Unlock()
return nil
}
// IsDebugLevel Returns true is debug lvl is enabled
func (l *LoggerT) IsDebugLevel() bool {
return levelDebug >= l.getLoggingLevel()
}
// Debug level logging.
// Most verbose logging level.
func (l *LoggerT) Debug(args ...interface{}) {
if levelDebug >= l.getLoggingLevel() {
Log.Debug(args...)
}
}
// Info level logging.
// Use this to log the state of the application. Dont use Logger.Info in the flow of individual events. Use Logger.Debug instead.
func (l *LoggerT) Info(args ...interface{}) {
if levelInfo >= l.getLoggingLevel() {
Log.Info(args...)
}
}
// Warn level logging.
// Use this to log warnings
func (l *LoggerT) Warn(args ...interface{}) {
if levelWarn >= l.getLoggingLevel() {
Log.Warn(args...)
}
}
// Error level logging.
// Use this to log errors which dont immediately halt the application.
func (l *LoggerT) Error(args ...interface{}) {
if levelError >= l.getLoggingLevel() {
Log.Error(args...)
}
}
// Fatal level logging.
// Use this to log errors which crash the application.
func (l *LoggerT) Fatal(args ...interface{}) {
if levelFatal >= l.getLoggingLevel() {
Log.Error(args...)
// If enableStackTrace is true, Zaplogger will take care of writing stacktrace to the file.
// Else, we are force writing the stacktrace to the file.
if !enableStackTrace {
byteArr := make([]byte, 2048)
n := runtime.Stack(byteArr, false)
stackTrace := string(byteArr[:n])
Log.Error(stackTrace)
}
_ = Log.Sync()
}
}
// Debugf does debug level logging similar to fmt.Printf.
// Most verbose logging level
func (l *LoggerT) Debugf(format string, args ...interface{}) {
if levelDebug >= l.getLoggingLevel() {
Log.Debugf(format, args...)
}
}
// Infof does info level logging similar to fmt.Printf.
// Use this to log the state of the application. Dont use Logger.Info in the flow of individual events. Use Logger.Debug instead.
func (l *LoggerT) Infof(format string, args ...interface{}) {
if levelInfo >= l.getLoggingLevel() {
Log.Infof(format, args...)
}
}
// Warnf does warn level logging similar to fmt.Printf.
// Use this to log warnings
func (l *LoggerT) Warnf(format string, args ...interface{}) {
if levelWarn >= l.getLoggingLevel() {
Log.Warnf(format, args...)
}
}
// Errorf does error level logging similar to fmt.Printf.
// Use this to log errors which dont immediately halt the application.
func (l *LoggerT) Errorf(format string, args ...interface{}) {
if levelError >= l.getLoggingLevel() {
Log.Errorf(format, args...)
}
}
// Fatalf does fatal level logging similar to fmt.Printf.
// Use this to log errors which crash the application.
func (l *LoggerT) Fatalf(format string, args ...interface{}) {
if levelFatal >= l.getLoggingLevel() {
Log.Errorf(format, args...)
// If enableStackTrace is true, Zaplogger will take care of writing stacktrace to the file.
// Else, we are force writing the stacktrace to the file.
if !enableStackTrace {
byteArr := make([]byte, 2048)
n := runtime.Stack(byteArr, false)
stackTrace := string(byteArr[:n])
Log.Error(stackTrace)
}
_ = Log.Sync()
}
}
// LogRequest reads and logs the request body and resets the body to original state.
func (l *LoggerT) LogRequest(req *http.Request) {
if levelEvent >= l.getLoggingLevel() {
defer func() { _ = req.Body.Close() }()
bodyBytes, _ := io.ReadAll(req.Body)
bodyString := string(bodyBytes)
req.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
// print raw request body for debugging purposes
Log.Debug("Request Body: ", bodyString)
}
}
func GetLoggingConfig() map[string]int {
return loggerLevelsCache
}