-
Notifications
You must be signed in to change notification settings - Fork 8
/
logging.go
497 lines (419 loc) · 14.1 KB
/
logging.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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
// Copyright (c) 2018 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package logging
import (
"fmt"
"io"
"os"
"path/filepath"
"runtime/debug"
"strings"
"time"
lumberjack "gopkg.in/natefinch/lumberjack.v2"
)
// Level type
type Level int
/*
Common use of different level:
"panic": Code crash
"error": Unusual event occurred (invalid input or system issue), so exiting code prematurely
"warning": Unusual event occurred (invalid input or system issue), but continuing
"info": Basic information, indication of major code paths
"debug": Additional information, indication of minor code branches
*/
const (
InvalidLevel Level = -1
PanicLevel Level = 1
ErrorLevel Level = 2
WarningLevel Level = 3
InfoLevel Level = 4
DebugLevel Level = 5
maximumLevel Level = DebugLevel
panicStr = "panic"
errorStr = "error"
warningStr = "warning"
infoStr = "info"
debugStr = "debug"
invalidStr = "invalid"
)
const (
defaultLogLevel = InfoLevel
defaultTimestampFormat = time.RFC3339Nano
logFileReqFailMsg = "cni-log: filename is required when logging to stderr is off - will not log anything\n"
logFileFailMsg = "cni-log: failed to set log file '%s'\n"
setLevelFailMsg = "cni-log: cannot set logging level to '%s'\n"
symlinkEvalFailMsg = "cni-log: unable to evaluate symbolic links on path '%v'"
emptyStringFailMsg = "cni-log: unable to resolve empty string"
structuredLoggingOddArguments = "must provide an even number of arguments for structured logging"
structuredPrefixerOddArguments = "prefixer must return an even number of arguments for structured logging"
)
var levelMap = map[string]Level{
panicStr: PanicLevel,
errorStr: ErrorLevel,
warningStr: WarningLevel,
infoStr: InfoLevel,
debugStr: DebugLevel,
}
var logger *lumberjack.Logger
var logWriter io.Writer
var logLevel Level
var logToStderr bool
var prefixer Prefixer
var structuredPrefixer StructuredPrefixer
// Prefixer creator interface. Implement this interface if you wish to create a custom prefix.
type Prefixer interface {
// Produces the prefix string. CNI-Log will call this function
// to request for the prefix when building the logging output and will pass in the appropriate
// log level of your log message.
CreatePrefix(Level) string
}
// PrefixerFunc implements the Prefixer interface. It allows passing a function instead of a struct as the prefixer.
type PrefixerFunc func(Level) string
// Produces the prefix string. CNI-Log will call this function
// to request for the prefix when building the logging output and will pass in the appropriate
// log level of your log message.
func (f PrefixerFunc) CreatePrefix(loggingLevel Level) string {
return f(loggingLevel)
}
// StructuredPrefixer creator interface. Implement this interface if you wish to to create a custom prefix for
// structured logging.
type StructuredPrefixer interface {
// Produces the prefix string for structured logging. CNI-Log will call this function
// to request for the prefix when building the logging output and will pass in the appropriate
// log level of your log message.
CreateStructuredPrefix(Level, string) []interface{}
}
// StructuredPrefixerFunc implements the StructuredPrefixer interface. It allows passing a function instead of a struct
// as the prefixer.
type StructuredPrefixerFunc func(Level, string) []interface{}
// Produces the prefix string for structured logging. CNI-Log will call this function
// to request for the prefix when building the logging output and will pass in the appropriate
// log level of your log message.
func (f StructuredPrefixerFunc) CreateStructuredPrefix(loggingLevel Level, msg string) []interface{} {
return f(loggingLevel, msg)
}
// Defines a default prefixer which will be used if a custom prefix is not provided. It implements both the Prefixer
// and the StructuredPrefixer interface.
type defaultPrefixer struct {
prefixFormat string
timeFormat string
}
// LogOptions defines the configuration of the lumberjack logger
type LogOptions struct {
MaxAge *int `json:"maxAge,omitempty"`
MaxSize *int `json:"maxSize,omitempty"`
MaxBackups *int `json:"maxBackups,omitempty"`
Compress *bool `json:"compress,omitempty"`
}
func init() {
initLogger()
}
func initLogger() {
logger = &lumberjack.Logger{}
// Set default options.
SetLogOptions(nil)
SetLogStderr(true)
SetLogFile("")
SetLogLevel(defaultLogLevel)
// Create the default prefixer
SetDefaultPrefixer()
SetDefaultStructuredPrefixer()
}
// CreatePrefix implements the Prefixer interface for the defaultPrefixer.
func (p *defaultPrefixer) CreatePrefix(loggingLevel Level) string {
return fmt.Sprintf(p.prefixFormat, time.Now().Format(p.timeFormat), loggingLevel)
}
// CreateStructuredPrefix implements the StructuredPrefixer interface for the defaultPrefixer.
func (p *defaultPrefixer) CreateStructuredPrefix(loggingLevel Level, message string) []interface{} {
return []interface{}{
"time", time.Now().Format(p.timeFormat),
"level", loggingLevel,
"msg", message,
}
}
// SetPrefixer allows overwriting the Prefixer with a custom one.
func SetPrefixer(p Prefixer) {
prefixer = p
}
// SetStructuredPrefixer allows overwriting the StructuredPrefixer with a custom one.
func SetStructuredPrefixer(p StructuredPrefixer) {
structuredPrefixer = p
}
// SetDefaultPrefixer sets the default Prefixer.
func SetDefaultPrefixer() {
defaultPrefix := &defaultPrefixer{
prefixFormat: "%s [%s] ",
timeFormat: defaultTimestampFormat,
}
SetPrefixer(defaultPrefix)
}
// SetDefaultStructuredPrefixer sets the default StructuredPrefixer.
func SetDefaultStructuredPrefixer() {
defaultStructuredPrefix := &defaultPrefixer{
timeFormat: defaultTimestampFormat,
}
SetStructuredPrefixer(defaultStructuredPrefix)
}
// Set the logging options (LogOptions)
func SetLogOptions(options *LogOptions) {
// give some default value
logger.MaxSize = 100
logger.MaxAge = 5
logger.MaxBackups = 5
logger.Compress = true
if options != nil {
if options.MaxAge != nil {
logger.MaxAge = *options.MaxAge
}
if options.MaxSize != nil {
logger.MaxSize = *options.MaxSize
}
if options.MaxBackups != nil {
logger.MaxBackups = *options.MaxBackups
}
if options.Compress != nil {
logger.Compress = *options.Compress
}
}
// Update the logWriter if necessary.
if isFileLoggingEnabled() {
logWriter = logger
}
}
// SetLogFile sets logging file.
func SetLogFile(filename string) {
// Allow logging to stderr only. Print an error a single time when this is set to the empty string but stderr
// logging is off.
if filename == "" {
if !logToStderr {
fmt.Fprint(os.Stderr, logFileReqFailMsg)
}
disableFileLogging()
return
}
fp, err := resolvePath(filename)
if err != nil {
fmt.Fprint(os.Stderr, err)
return
}
if !isLogFileWritable(fp) {
fmt.Fprintf(os.Stderr, logFileFailMsg, filename)
return
}
logger.Filename = filename
logWriter = logger
}
// disableFileLogging disables file logging.
func disableFileLogging() {
logger.Filename = ""
logWriter = nil
}
// isFileLoggingEnabled returns true if file logging is enabled.
func isFileLoggingEnabled() bool {
return logWriter != nil
}
// GetLogLevel gets current logging level
func GetLogLevel() Level {
return logLevel
}
// SetLogLevel sets logging level
func SetLogLevel(level Level) {
if validateLogLevel(level) {
logLevel = level
} else {
fmt.Fprintf(os.Stderr, setLevelFailMsg, level)
}
}
func StringToLevel(level string) Level {
if l, found := levelMap[strings.ToLower(level)]; found {
return l
}
return InvalidLevel
}
// SetLogStderr sets flag for logging stderr output
func SetLogStderr(enable bool) {
if !enable && !isFileLoggingEnabled() {
fmt.Fprint(os.Stderr, logFileReqFailMsg)
}
logToStderr = enable
}
// String converts a Level into its string representation.
func (l Level) String() string {
switch l {
case PanicLevel:
return panicStr
case WarningLevel:
return warningStr
case InfoLevel:
return infoStr
case ErrorLevel:
return errorStr
case DebugLevel:
return debugStr
case InvalidLevel:
return invalidStr
default:
return invalidStr
}
}
// SetOutput set custom output WARNING subsequent call to SetLogFile or SetLogOptions invalidates this setting
func SetOutput(out io.Writer) {
logWriter = out
}
// Panicf prints logging plus stack trace. This should be used only for unrecoverable error
func Panicf(format string, a ...interface{}) {
printf(PanicLevel, format, a...)
printf(PanicLevel, "========= Stack trace output ========")
printf(PanicLevel, "%+v", string(debug.Stack()))
printf(PanicLevel, "========= Stack trace output end ========")
}
// PanicStructured provides structured logging for log level >= panic.
func PanicStructured(msg string, args ...interface{}) {
stackTrace := string(debug.Stack())
args = append(args, "stacktrace", stackTrace)
m := structuredMessage(PanicLevel, msg, args...)
printWithPrefixf(PanicLevel, false, m)
}
// Errorf prints logging if logging level >= error
func Errorf(format string, a ...interface{}) error {
printf(ErrorLevel, format, a...)
return fmt.Errorf(format, a...)
}
// ErrorStructured provides structured logging for log level >= error.
func ErrorStructured(msg string, args ...interface{}) error {
m := structuredMessage(ErrorLevel, msg, args...)
printWithPrefixf(ErrorLevel, false, m)
return fmt.Errorf("%s", m)
}
// Warningf prints logging if logging level >= warning
func Warningf(format string, a ...interface{}) {
printf(WarningLevel, format, a...)
}
// WarningStructured provides structured logging for log level >= warning.
func WarningStructured(msg string, args ...interface{}) {
m := structuredMessage(WarningLevel, msg, args...)
printWithPrefixf(WarningLevel, false, m)
}
// Infof prints logging if logging level >= info
func Infof(format string, a ...interface{}) {
printf(InfoLevel, format, a...)
}
// InfoStructured provides structured logging for log level >= info.
func InfoStructured(msg string, args ...interface{}) {
m := structuredMessage(InfoLevel, msg, args...)
printWithPrefixf(InfoLevel, false, m)
}
// Debugf prints logging if logging level >= debug
func Debugf(format string, a ...interface{}) {
printf(DebugLevel, format, a...)
}
// DebugStructured provides structured logging for log level >= debug.
func DebugStructured(msg string, args ...interface{}) {
m := structuredMessage(DebugLevel, msg, args...)
printWithPrefixf(DebugLevel, false, m)
}
// structuredMessage takes msg and an even list of args and returns a structured message.
func structuredMessage(loggingLevel Level, msg string, args ...interface{}) string {
prefixArgs := structuredPrefixer.CreateStructuredPrefix(loggingLevel, msg)
if len(prefixArgs)%2 != 0 {
panic(fmt.Sprintf("msg=%q logging_failure=%q", msg, structuredPrefixerOddArguments))
}
var output []string
for i := 0; i < len(prefixArgs)-1; i += 2 {
output = append(output, fmt.Sprintf("%s=%q", argToString(prefixArgs[i]), argToString(prefixArgs[i+1])))
}
if len(args)%2 != 0 {
output = append(output, fmt.Sprintf("logging_failure=%q", structuredLoggingOddArguments))
panic(strings.Join(output, " "))
}
for i := 0; i < len(args)-1; i += 2 {
output = append(output, fmt.Sprintf("%s=%q", argToString(args[i]), argToString(args[i+1])))
}
return strings.Join(output, " ")
}
// argToString returns the string representation of the provided interface{}.
func argToString(arg interface{}) string {
return fmt.Sprintf("%+v", arg)
}
// doWritef takes care of the low level writing to the output io.Writer.
func doWritef(writer io.Writer, format string, a ...interface{}) {
fmt.Fprintf(writer, format, a...)
fmt.Fprintf(writer, "\n")
}
// printf prints log messages if they match the configured log level. A configured prefix is prepended to messages.
func printf(level Level, format string, a ...interface{}) {
printWithPrefixf(level, true, format, a...)
}
// printWithPrefixf prints log messages if they match the configured log level. Messages are optionally prepended by a
// configured prefix.
func printWithPrefixf(level Level, printPrefix bool, format string, a ...interface{}) {
if level > logLevel {
return
}
if !isFileLoggingEnabled() && !logToStderr {
return
}
if printPrefix {
format = prefixer.CreatePrefix(level) + format
}
if logToStderr {
doWritef(os.Stderr, format, a...)
}
if isFileLoggingEnabled() {
doWritef(logWriter, format, a...)
}
}
// isLogFileWritable checks if the path can be written to. If the file does not exist yet, the entire path including
// the file will be created.
func isLogFileWritable(filename string) bool {
logFileDirs := filepath.Dir(filename)
// Check if parent directories of log file exists
// If not exist, try to create the parent directories.
// If exists, check that a log file can be created in that directory
if _, err := os.Stat(logFileDirs); os.IsNotExist(err) {
if err = os.MkdirAll(logFileDirs, 0755); err != nil {
// failed to create parent dirs. Assuming no write permissions
return false
}
}
f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
return false
}
f.Close()
return true
}
func isSymLink(path string) bool {
info, err := os.Lstat(path)
if err != nil {
return false
}
if info.Mode()&os.ModeSymlink == os.ModeSymlink {
return true
}
return false
}
// resolvePath will try to resolve the provided path. If path is empty or is a symlink, return an error.
func resolvePath(path string) (string, error) {
if path == "" {
return "", fmt.Errorf(emptyStringFailMsg)
}
if isSymLink(path) {
return "", fmt.Errorf(symlinkEvalFailMsg, path)
}
return filepath.Clean(path), nil
}
func validateLogLevel(level Level) bool {
return level > 0 && level <= maximumLevel
}