-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcustomlogger.go
87 lines (71 loc) · 2.38 KB
/
customlogger.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
package yalp
import (
"os"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// CustomLogger is a customizable logging.Logger where you can choose the level
// and the zapcore encoder configuration.
type CustomLogger struct {
logger *zap.Logger
level zap.AtomicLevel
output *os.File
config zapcore.EncoderConfig
}
var _ Logger = &CustomLogger{}
// NewCustomLogger returns a custom logging
// object for the Classy service to use.
func NewCustomLogger(level []byte, config zapcore.EncoderConfig) *CustomLogger {
logLevel := zap.NewAtomicLevel()
logLevel.UnmarshalText(level)
return &CustomLogger{
level: logLevel,
config: config,
output: os.Stdout,
logger: zap.New(zapcore.NewCore(zapcore.NewJSONEncoder(config), zapcore.Lock(os.Stdout), logLevel)),
}
}
// Info logs at an info level.
func (l *CustomLogger) Info(msg string, iFields ...interface{}) {
fields := interfaceToZapField(iFields...)
l.logger.Info(msg, fields...)
}
// Debug logs at an debug level.
func (l *CustomLogger) Debug(msg string, iFields ...interface{}) {
fields := interfaceToZapField(iFields...)
l.logger.Debug(msg, fields...)
}
// Warn warns the client.
func (l *CustomLogger) Warn(msg string, iFields ...interface{}) {
fields := interfaceToZapField(iFields...)
l.logger.Warn(msg, fields...)
}
// Error logs at an error level.
func (l *CustomLogger) Error(msg string, iFields ...interface{}) {
fields := interfaceToZapField(iFields...)
l.logger.Error(msg, fields...)
}
// Fatal logs at a fatal level and exits.
func (l *CustomLogger) Fatal(msg string, iFields ...interface{}) {
fields := interfaceToZapField(iFields...)
l.logger.Fatal(msg, fields...)
}
// SetLevel changes the logger level
func (l *CustomLogger) SetLevel(level []byte) {
// flush the existing logger before changing to new log level
l.logger.Sync()
// Read in the new zapcore AtomicLevel and apply new zap instance
l.level.UnmarshalText(level)
l.logger = zap.New(zapcore.NewCore(zapcore.NewJSONEncoder(l.config), zapcore.Lock(l.output), l.level))
}
// SetOutput changes the output
func (l *CustomLogger) SetOutput(output *os.File) {
// flush the existing logger before changing to new log output
l.logger.Sync()
// set the new output and apply new zap instance
l.output = output
l.logger = zap.New(zapcore.NewCore(zapcore.NewJSONEncoder(l.config), zapcore.Lock(l.output), l.level))
}
func (l *CustomLogger) Sync() error {
return l.logger.Sync()
}