forked from Elara6331/logger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.go
342 lines (289 loc) · 8.99 KB
/
cli.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
package logger
import (
"bufio"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"os"
"strconv"
"time"
"github.com/gookit/color"
"github.com/mattn/go-isatty"
)
var _ Logger = (*CLILogger)(nil)
// CLILogger is a logger meant to be used for CLI tools
// where users will view and read the logs throughout the
// application's execution
type CLILogger struct {
Out io.Writer
Level LogLevel
UseColor bool
noPanic bool
noExit bool
MsgColor color.Color
KeyColor color.Color
DebugColor color.Color
InfoColor color.Color
WarnColor color.Color
ErrColor color.Color
FatalColor color.Color
PanicColor color.Color
}
// NewCLI creates and returns a new CLILogger
func NewCLI(out io.Writer) *CLILogger {
useColor := false
if f, ok := out.(*os.File); ok {
useColor = isatty.IsTerminal(f.Fd())
}
return &CLILogger{
Out: out,
Level: LogLevelInfo,
UseColor: useColor,
MsgColor: color.Normal,
KeyColor: color.FgCyan,
DebugColor: color.FgMagenta,
InfoColor: color.FgGreen,
WarnColor: color.FgYellow,
ErrColor: color.FgLightRed,
FatalColor: color.FgRed.Darken(),
PanicColor: color.FgRed.Darken(),
}
}
// NoPanic prevents the logger from panicking on panic events
func (pl *CLILogger) NoPanic() {
pl.noPanic = true
}
// NoExit prevents the logger from exiting on fatal events
func (pl *CLILogger) NoExit() {
pl.noExit = true
}
// SetLevel sets the log level of the logger
func (pl *CLILogger) SetLevel(l LogLevel) {
pl.Level = l
}
// Debug creates a new debug event with the given message
func (pl *CLILogger) Debug(msg string) LogBuilder {
return newCLILogBuilder(pl, msg, LogLevelDebug)
}
// Debugf creates a new debug event with the formatted message
func (pl *CLILogger) Debugf(format string, v ...any) LogBuilder {
return newCLILogBuilder(pl, fmt.Sprintf(format, v...), LogLevelDebug)
}
// Info creates a new info event with the given message
func (pl *CLILogger) Info(msg string) LogBuilder {
return newCLILogBuilder(pl, msg, LogLevelInfo)
}
// Infof creates a new info event with the formatted message
func (pl *CLILogger) Infof(format string, v ...any) LogBuilder {
return newCLILogBuilder(pl, fmt.Sprintf(format, v...), LogLevelInfo)
}
// Warn creates a new warn event with the given message
func (pl *CLILogger) Warn(msg string) LogBuilder {
return newCLILogBuilder(pl, msg, LogLevelWarn)
}
// Warnf creates a new warn event with the formatted message
func (pl *CLILogger) Warnf(format string, v ...any) LogBuilder {
return newCLILogBuilder(pl, fmt.Sprintf(format, v...), LogLevelWarn)
}
// Error creates a new error event with the given message
func (pl *CLILogger) Error(msg string) LogBuilder {
return newCLILogBuilder(pl, msg, LogLevelError)
}
// Errorf creates a new error event with the formatted message
func (pl *CLILogger) Errorf(format string, v ...any) LogBuilder {
return newCLILogBuilder(pl, fmt.Sprintf(format, v...), LogLevelError)
}
// Fatal creates a new fatal event with the given message
//
// When sent, fatal events will cause a call to os.Exit(1)
func (pl *CLILogger) Fatal(msg string) LogBuilder {
return newCLILogBuilder(pl, msg, LogLevelFatal)
}
// Fatalf creates a new fatal event with the formatted message
//
// When sent, fatal events will cause a call to os.Exit(1)
func (pl *CLILogger) Fatalf(format string, v ...any) LogBuilder {
return newCLILogBuilder(pl, fmt.Sprintf(format, v...), LogLevelFatal)
}
// Panic creates a new panic event with the given message
//
// When sent, panic events will cause a panic
func (pl *CLILogger) Panic(msg string) LogBuilder {
return newCLILogBuilder(pl, msg, LogLevelPanic)
}
// Panicf creates a new panic event with the formatted message
//
// When sent, panic events will cause a panic
func (pl *CLILogger) Panicf(format string, v ...any) LogBuilder {
return newCLILogBuilder(pl, fmt.Sprintf(format, v...), LogLevelPanic)
}
// CLILogBuilder implements the LogBuilder interface
// using human-readable output for log messages
type CLILogBuilder struct {
l *CLILogger
lvl LogLevel
out *bufio.Writer
}
func newCLILogBuilder(pl *CLILogger, msg string, lvl LogLevel) LogBuilder {
if pl.Out == io.Discard || lvl < pl.Level {
return NopLogBuilder{}
}
lb := &CLILogBuilder{
l: pl,
out: bufio.NewWriter(pl.Out),
lvl: lvl,
}
switch lvl {
case LogLevelDebug:
lb.writeColor(lb.l.DebugColor, "[DBG]")
case LogLevelInfo:
lb.writeColor(lb.l.InfoColor, "-->")
case LogLevelWarn:
lb.writeColor(lb.l.WarnColor, " ->")
case LogLevelError:
lb.writeColor(lb.l.ErrColor, " ->")
case LogLevelFatal:
lb.writeColor(lb.l.FatalColor, " ->")
case LogLevelPanic:
lb.writeColor(lb.l.PanicColor, " ->")
}
lb.out.WriteByte(' ')
lb.writeColor(lb.l.MsgColor, msg)
return lb
}
// writeKey writes a JSON key to the buffer
func (plb *CLILogBuilder) writeKey(k string) {
plb.out.WriteByte(' ')
plb.writeColor(plb.l.KeyColor, k)
plb.out.WriteByte('=')
}
// Int adds an int field to the output
func (plb *CLILogBuilder) Int(key string, val int) LogBuilder {
return plb.Int64(key, int64(val))
}
// Int64 adds an int64 field to the output
func (plb *CLILogBuilder) Int64(key string, val int64) LogBuilder {
plb.writeKey(key)
plb.out.WriteString(strconv.FormatInt(val, 10))
return plb
}
// Int32 adds an int32 field to the output
func (plb *CLILogBuilder) Int32(key string, val int32) LogBuilder {
return plb.Int64(key, int64(val))
}
// Int16 adds an int16 field to the output
func (plb *CLILogBuilder) Int16(key string, val int16) LogBuilder {
return plb.Int64(key, int64(val))
}
// Int8 adds an int8 field to the output
func (plb *CLILogBuilder) Int8(key string, val int8) LogBuilder {
return plb.Int64(key, int64(val))
}
// Uint adds a uint field to the output
func (plb *CLILogBuilder) Uint(key string, val uint) LogBuilder {
return plb.Uint64(key, uint64(val))
}
// Uint64 adds a uint64 field to the output
func (plb *CLILogBuilder) Uint64(key string, val uint64) LogBuilder {
plb.writeKey(key)
plb.out.WriteString(strconv.FormatUint(val, 10))
return plb
}
// Uint32 adds a uint32 field to the output
func (plb *CLILogBuilder) Uint32(key string, val uint32) LogBuilder {
return plb.Uint64(key, uint64(val))
}
// Uint16 adds a uint16 field to the output
func (plb *CLILogBuilder) Uint16(key string, val uint16) LogBuilder {
return plb.Uint64(key, uint64(val))
}
// Uint8 adds a uint8 field to the output
func (plb *CLILogBuilder) Uint8(key string, val uint8) LogBuilder {
return plb.Uint64(key, uint64(val))
}
// float adds a float of specified bitsize to the output
func (plb *CLILogBuilder) float(key string, val float64, bitsize int) LogBuilder {
plb.writeKey(key)
plb.out.WriteString(strconv.FormatFloat(val, 'f', -1, bitsize))
return plb
}
// Float64 adds a float64 field to the output
func (plb *CLILogBuilder) Float64(key string, val float64) LogBuilder {
return plb.float(key, val, 64)
}
// Float32 adds a float32 field to the output
func (plb *CLILogBuilder) Float32(key string, val float32) LogBuilder {
return plb.float(key, float64(val), 32)
}
// Stringer calls the String method of an fmt.Stringer
// and adds the resulting string as a field to the output
func (plb *CLILogBuilder) Stringer(key string, s fmt.Stringer) LogBuilder {
return plb.Str(key, s.String())
}
// Bytes writes hex-encoded bytes as a field to the output
func (plb *CLILogBuilder) Bytes(key string, b []byte) LogBuilder {
return plb.Str(key, hex.EncodeToString(b))
}
// Timestamp adds the time formatted as RFC3339Nano
// as a field to the output
func (plb *CLILogBuilder) Timestamp() LogBuilder {
return plb.Str("timestamp", time.Now().Format(time.RFC3339Nano))
}
// Bool adds a bool as a field to the output
func (plb *CLILogBuilder) Bool(key string, val bool) LogBuilder {
plb.writeKey(key)
if val {
plb.out.WriteString("true")
} else {
plb.out.WriteString("false")
}
return plb
}
// Str adds a string as a field to the output
func (plb *CLILogBuilder) Str(key, val string) LogBuilder {
plb.writeKey(key)
plb.out.WriteByte('"')
plb.out.WriteString(val)
plb.out.WriteByte('"')
return plb
}
// Any uses reflection to marshal any type and writes
// the result as a field to the output. This is much slower
// than the type-specific functions.
func (plb *CLILogBuilder) Any(key string, val any) LogBuilder {
plb.writeKey(key)
data, err := json.Marshal(val)
if err != nil {
panic(err)
}
plb.out.Write(data)
return plb
}
// Err adds an error as a field to the output
func (plb *CLILogBuilder) Err(err error) LogBuilder {
plb.out.WriteByte(' ')
plb.writeColor(plb.l.ErrColor, "error=")
plb.writeColor(plb.l.ErrColor, `"`+err.Error()+`"`)
return plb
}
// Send sends the event to the output.
//
// After calling send, do not use the event again.
func (plb *CLILogBuilder) Send() {
plb.out.WriteByte('\n')
plb.out.Flush()
if plb.lvl == LogLevelFatal && !plb.l.noExit {
os.Exit(1)
} else if plb.lvl == LogLevelPanic && !plb.l.noPanic {
panic("")
}
}
// writeColor writes a string to the buffer using the given color
func (plb *CLILogBuilder) writeColor(c color.Color, s string) {
if plb.l.UseColor {
plb.out.WriteString(c.Text(s))
} else {
plb.out.WriteString(s)
}
}