-
Notifications
You must be signed in to change notification settings - Fork 170
/
log.go
128 lines (108 loc) · 2.5 KB
/
log.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
package utils
import (
"encoding"
"encoding/json"
"errors"
"time"
"github.com/cockroachdb/pebble"
"github.com/spf13/pflag"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
var ErrUnknownLogLevel = errors.New("unknown log level (known: debug, info, warn, error)")
type LogLevel int
// The following are necessary for Cobra and Viper, respectively, to unmarshal log level
// CLI/config parameters properly.
var (
_ pflag.Value = (*LogLevel)(nil)
_ encoding.TextUnmarshaler = (*LogLevel)(nil)
)
const (
DEBUG LogLevel = iota
INFO
WARN
ERROR
)
func (l LogLevel) String() string {
switch l {
case DEBUG:
return "debug"
case INFO:
return "info"
case WARN:
return "warn"
case ERROR:
return "error"
default:
// Should not happen.
panic(ErrUnknownLogLevel)
}
}
func (l LogLevel) MarshalYAML() (interface{}, error) {
return l.String(), nil
}
func (l *LogLevel) Set(s string) error {
switch s {
case "DEBUG", "debug":
*l = DEBUG
case "INFO", "info":
*l = INFO
case "WARN", "warn":
*l = WARN
case "ERROR", "error":
*l = ERROR
default:
return ErrUnknownLogLevel
}
return nil
}
func (l *LogLevel) Type() string {
return "LogLevel"
}
func (l *LogLevel) MarshalJSON() ([]byte, error) {
return json.RawMessage(`"` + l.String() + `"`), nil
}
func (l *LogLevel) UnmarshalText(text []byte) error {
return l.Set(string(text))
}
type Logger interface {
SimpleLogger
pebble.Logger
}
type SimpleLogger interface {
Debugw(msg string, keysAndValues ...any)
Infow(msg string, keysAndValues ...any)
Warnw(msg string, keysAndValues ...any)
Errorw(msg string, keysAndValues ...any)
}
type ZapLogger struct {
*zap.SugaredLogger
}
var _ Logger = (*ZapLogger)(nil)
func NewNopZapLogger() *ZapLogger {
return &ZapLogger{zap.NewNop().Sugar()}
}
func NewZapLogger(logLevel LogLevel, colour bool) (*ZapLogger, error) {
config := zap.NewProductionConfig()
config.Encoding = "console"
config.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
if !colour {
config.EncoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
}
config.EncoderConfig.EncodeTime = func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(t.Local().Format("15:04:05.000 02/01/2006 -07:00"))
}
level, err := zapcore.ParseLevel(logLevel.String())
if err != nil {
return nil, err
}
config.Level.SetLevel(level)
log, err := config.Build()
if err != nil {
return nil, err
}
return &ZapLogger{log.Sugar()}, nil
}
func (l *ZapLogger) Warningf(msg string, args ...any) {
l.Warnf(msg, args)
}