-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
435 lines (372 loc) · 12.8 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
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
package glog
import (
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"time"
)
type Logger struct {
ID string
color int
debugMode bool
traceMode bool
traceLevel uint
file string
fileColor string
onMessage func(string)
}
// EnableTrace enables trace mode for the logger with the given trace level.
// When trace mode is enabled, calls to Logger.Trace(level) with a severity level
// equal to or higher than the specified trace level will trigger a stack trace print.
func (l *Logger) EnableTrace(level uint) {
l.traceMode = true
l.traceLevel = level
}
// DisableTrace disables trace mode for the logger.
func (l *Logger) DisableTrace() {
l.traceMode = false
}
// EnableDebug enables debug mode for the logger.
// When debug mode is enabled, calls to Logger.Debug(...) will be printed to the output.
func (l *Logger) EnableDebug() {
l.debugMode = true
}
// DisableDebug disables debug mode for the logger.
func (l *Logger) DisableDebug() {
l.debugMode = false
}
// EnablePlainLog enables logging to a plain text file with the given file path.
// Each log message, stripped of ANSI escapes, will be appended to the file.
// File logging can be enabled/disabled on the fly.
func (l *Logger) EnablePlainLog(path string) {
l.file = path
}
// DisablePlainLog stops logging plaintext messages to a file.
// File logging can be enabled/disabled on the fly.
func (l *Logger) DisablePlainLog() {
l.file = ""
}
// EnableColorLog enables logging to a text file with the given file path.
// Each log message, together with ANSI escapes, will be appended to the file.
func (l *Logger) EnableColorLog(path string) {
l.fileColor = path
}
// DisableColorLog stops logging messages to a file.
func (l *Logger) DisableColorLog() {
l.fileColor = ""
}
// write logs a message to the console or file with an optional indicator,
// and applies various formatting options as specified in the logger's configuration.
//
// If a progress indicator ('p') is specified, it will be displayed as a progress bar
// and continuously replaced on the same line using ANSI escape sequences.
//
// The 'format' parameter is a string that can contain verbs, as specified by the fmt package,
// and the 'a' parameter provides the corresponding arguments for each verb.
//
// If a message handler function was specified during logger creation, the formatted message
// will be passed to it instead of being printed to the console or file.
//
// If the logger is configured to use colors, the message will include ANSI escape sequences
// to apply the appropriate colors for the message elements.
//
// If a file has been specified for the logger, the message will be appended to the file.
// If a color file has also been specified, the message with color codes will be appended to that file.
// If the logger's configuration disables colors, any color codes will be stripped from the message.
//
// Related config setting(s):
//
// - LoggerConfig.ShowIndicator
// - LoggerConfig.ShowDateTime
// - LoggerConfig.ShowRuntimeSeconds
// - LoggerConfig.ShowRuntimeMilliseconds
// - LoggerConfig.ColorsDisabled
// - LoggerConfig.Indicators
func (l *Logger) write(indicator rune, format string, a ...interface{}) {
prefix := ""
if LoggerConfig.ShowIndicator {
if vi, ok := LoggerConfig.Indicators[indicator]; ok {
prefix = Wrap(vi.value, vi.color)
}
}
if LoggerConfig.ShowRuntimeSeconds {
prefix = fmt.Sprintf("%22s s %s", Runtime(), prefix)
}
if LoggerConfig.ShowRuntimeMilliseconds {
prefix = fmt.Sprintf("%22s ms %s", RuntimeMilliseconds(), prefix)
}
if LoggerConfig.ShowDateTime {
prefix = fmt.Sprintf("%s %s", DateTime(time.Now()), prefix)
}
if LoggerConfig.ShowSubsystem {
prefix = fmt.Sprintf("%s %s: ", prefix, Wrap(fmt.Sprintf("%-16s", l.ID), l.color))
}
msg := fmt.Sprintf(format, a...)
if LoggerConfig.SplitOnNewLine {
res := []string{}
for _, ln := range strings.Split(msg, "\n") {
res = append(res, prefix+" "+ln)
}
msg = strings.Join(res, "\n")
} else {
msg = prefix + " " + msg
}
if indicator == 'p' {
// the progress indicator is special, let's add some magic:
msg = StoreCursor() + ClearToEOL() + msg + RestoreCursor()
} else {
msg += "\n"
}
if l.onMessage != nil {
l.onMessage(msg)
return
}
if LoggerConfig.ColorsDisabled {
msg = StripANSI(msg)
}
if l.file != "" {
err := os.MkdirAll(filepath.Dir(l.file), 0770) // create target dir if it doesn't exist
if err != nil {
panic(err)
}
f, err := os.OpenFile(l.file, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
panic(err)
}
defer f.Close()
if _, err = f.WriteString(StripANSI(msg)); err != nil {
panic(err)
}
}
if l.fileColor != "" {
err := os.MkdirAll(filepath.Dir(l.fileColor), 0770) // create target dir if it doesn't exist
if err != nil {
panic(err)
}
f, err := os.OpenFile(l.fileColor, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
panic(err)
}
defer f.Close()
if _, err = f.WriteString(msg); err != nil {
panic(err)
}
}
fmt.Print(msg)
}
// auto prints a message using the given indicator, but will first run all arguments
// through glog.Auto()
func (l *Logger) auto(indicator rune, format string, a ...interface{}) {
str := []interface{}{}
for _, s := range a {
str = append(str, Auto(s))
}
l.write(indicator, format, str...)
}
// Blank prints a message without any indicator such as "[ ]", "[i]", etc.
func (l *Logger) Blank(format string, a ...interface{}) {
l.write('_', format, a...)
}
// BlankAuto does the same as Blank but will process all arguments with glog.Auto(...) first.
func (l *Logger) BlankAuto(format string, a ...interface{}) {
l.auto('_', format, a...)
}
func (l *Logger) Default(format string, a ...interface{}) {
l.write(' ', format, a...)
}
// DefaultAuto does the same as Default but will process all arguments with glog.Auto(...) first.
func (l *Logger) DefaultAuto(format string, a ...interface{}) {
l.auto(' ', format, a...)
}
func (l *Logger) Info(format string, a ...interface{}) {
l.write('i', format, a...)
}
// InfoAuto does the same as Info but will process all arguments with glog.Auto(...) first.
func (l *Logger) InfoAuto(format string, a ...interface{}) {
l.auto('i', format, a...)
}
func (l *Logger) Success(format string, a ...interface{}) {
l.write('✓', format, a...)
}
// SuccessAuto does the same as Success but will process all arguments with glog.Auto(...) first.
func (l *Logger) SuccessAuto(format string, a ...interface{}) {
l.auto('✓', format, a...)
}
func (l *Logger) OK(format string, a ...interface{}) {
l.write('+', format, a...)
}
// OKAuto does the same as OK but will process all arguments with glog.Auto(...) first.
func (l *Logger) OKAuto(format string, a ...interface{}) {
l.auto('+', format, a...)
}
func (l *Logger) NotOK(format string, a ...interface{}) {
l.write('-', format, a...)
}
// NotOKAuto does the same as NotOK but will process all arguments with glog.Auto(...) first.
func (l *Logger) NotOKAuto(format string, a ...interface{}) {
l.auto('-', format, a...)
}
func (l *Logger) Error(format string, a ...interface{}) {
l.write('x', format, a...)
}
// ErrorAuto does the same as Error but will process all arguments with glog.Auto(...) first.
func (l *Logger) ErrorAuto(format string, a ...interface{}) {
l.auto('x', format, a...)
}
func (l *Logger) Warning(format string, a ...interface{}) {
l.write('!', format, a...)
}
// WarningAuto does the same as Warning but will process all arguments with glog.Auto(...) first.
func (l *Logger) WarningAuto(format string, a ...interface{}) {
l.auto('!', format, a...)
}
func (l *Logger) Debug(format string, a ...interface{}) {
if !l.debugMode {
return
}
l.write('d', format, a...)
}
// DebugAuto does the same as Debug but will process all arguments with glog.Auto(...) first.
func (l *Logger) DebugAuto(format string, a ...interface{}) {
if !l.debugMode {
return
}
l.auto('d', format, a...)
}
func (l *Logger) Question(format string, a ...interface{}) {
l.write('?', format, a...)
}
// QuestionAuto does the same as Question but will process all arguments with glog.Auto(...) first.
func (l *Logger) QuestionAuto(format string, a ...interface{}) {
l.auto('?', format, a...)
}
func (l *Logger) Trace(level uint) {
if !l.traceMode || level > l.traceLevel {
return
}
stackTracer.Sample(0).PrintWithLogger(l, 't')
}
func (l *Logger) ShowColors() {
str := ""
for i := 0; i < 8; i++ {
str += Wrap(fmt.Sprintf("%03d ", i), i)
}
l.Default("%s", str)
str = ""
for i := 8; i < 16; i++ {
str += Wrap(fmt.Sprintf("%03d ", i), i)
}
l.Default("%s", str)
for i := 16; i < 256; i++ {
str := ""
for j := 0; j < 12 && i < 256; j++ {
str += Wrap(fmt.Sprintf("%03d ", i), i)
i++
}
i--
l.Default("%s", str)
}
}
func (l *Logger) Table(ats ...*TableColumn) {
NewTable(ats...).Print(l)
}
func (l *Logger) TableWithoutHeader(ats ...*TableColumn) {
NewTable(ats...).PrintWithoutHeader(l)
}
func (l *Logger) KeyValueTable(data map[string]interface{}) {
atsKeys := NewTableColumnLeft("Key")
atsValues := NewTableColumnLeft("Value")
keys := []string{}
for k := range data {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
atsKeys.Push(k)
atsValues.Push(data[k])
}
NewTable(atsKeys, atsValues).Print(l)
}
// Progress prints a progress bar followed by the given format and arguments.
// This uses ANSI escapes to continuously replace the same line on the terminal.
// Use the methods ProgressSuccess and ProgressError to end a progress.
// This will print a message of the corresponding type and advance to the next line.
//
// It uses the format string and arguments to print additional information
// alongside the progress bar. The progress parameter should be a float between
// 0 and 1, representing the progress percentage as a decimal. The progress bar
// width is determined by the LoggerConfig.ProgressBarWidth configuration setting.
//
// Related config setting(s):
// - LoggerConfig.ProgressBarWidth
//
// See also:
// - Logger.ProgressSuccess
// - Logger.ProgressError
func (l *Logger) Progress(progress float64, format string, a ...interface{}) {
a = append([]interface{}{ProgressBar(progress, LoggerConfig.ProgressBarWidth)}, a...)
l.write('p', "%s "+format, a...)
}
// ProgressSuccess prints a success message with a progress bar followed by the given format and arguments.
// This method works in conjunction with Progress to advance the cursor to the next line
// once the progress has finished.
//
// It uses the format string and arguments to print additional information
// alongside the progress bar. The progress parameter should be a float between
// 0 and 1, representing the progress percentage as a decimal. The progress bar
// width is determined by the LoggerConfig.ProgressBarWidth configuration setting.
//
// Related config setting(s):
// - LoggerConfig.ProgressBarWidth
//
// See also:
// - Logger.Progress
// - Logger.ProgressError
func (l *Logger) ProgressSuccess(progress float64, format string, a ...interface{}) {
a = append([]interface{}{ClearToEOL(), ProgressBar(progress, LoggerConfig.ProgressBarWidth)}, a...)
l.Success("%s%s "+format, a...)
}
// ProgressError prints an error message with a progress bar followed by the given format and arguments.
// This method works in conjunction with Progress to advance the cursor to the next line
// once the progress has finished.
//
// It uses the format string and arguments to print additional information
// alongside the progress bar. The progress parameter should be a float between
// 0 and 1, representing the progress percentage as a decimal. The progress bar
// width is determined by the LoggerConfig.ProgressBarWidth configuration setting.
//
// Related config setting(s):
// - LoggerConfig.ProgressBarWidth
//
// See also:
// - Logger.Progress
// - Logger.ProgressSuccess
func (l *Logger) ProgressError(progress float64, format string, a ...interface{}) {
a = append([]interface{}{ClearToEOL(), ProgressBar(progress, LoggerConfig.ProgressBarWidth)}, a...)
l.Error("%s%s "+format, a...)
}
// NewLogger creates a new Logger instance with the given ID and settings.
// If `color` is set to `-1`, a color will be chosen automatically based on the ID.
// If `debugMode` is set to `true`, debug level logging will be enabled.
// If `messageHandler` is not `nil`, the logger will write to the provided handler instead of the screen.
func NewLogger(id string, color int, debugMode bool, messageHandler func(string)) *Logger {
if color == -1 {
color = stringColorCache.Get(id)
}
return &Logger{
ID: id,
color: color,
file: "",
fileColor: "",
debugMode: debugMode,
onMessage: messageHandler,
traceMode: false,
traceLevel: 0,
}
}
// NewLoggerSimple creates a new Logger instance with the given ID, automatically chosen color, and without debug mode or message handler.
func NewLoggerSimple(id string) *Logger {
return NewLogger(id, -1, false, nil)
}