/
log.go
1397 lines (1267 loc) · 39.1 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
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This was created based on log/log.go from the Go source, imported originally from
// https://github.com/golang/go/blob/692054e76e7686c6d5de385df69873e6427a35fb/src/log/log.go
// Portions Copyright 2015 Dan Tillberg. Those portions
// are licensed for use according to the ISC License.
// The original copyright notice is below:
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package log implements a simple logging package. It defines a type, Logger,
// with methods for formatting output. It also has a predefined 'standard'
// Logger accessible through helper functions Print[f|ln], Fatal[f|ln], and
// Panic[f|ln], which are easier to use than creating a Logger manually.
// That logger writes to standard error and prints the date and time
// of each logged message.
// The Fatal functions call os.Exit(1) after writing the log message.
// The Panic functions call panic after writing the log message.
package alog
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"os/exec"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
)
// These flags define which text to prefix to each log entry generated by the Logger.
const (
// Bits or'ed together to control what's printed.
// There is no control over the order they appear (the order listed
// here) or the format they present (as described in the comments).
// The prefix is followed by a colon only when Llongfile or Lshortfile
// is specified.
// For example, flags Ldate | Ltime (or LstdFlags) produce,
// 2009/01/23 01:23:23 message
// while flags Ldate | Ltime | Lmicroseconds | Llongfile produce,
// 2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message
Ldate = 1 << iota // the date in the local time zone: 2009/01/23
Ltime // the time in the local time zone: 01:23:23
Lmicroseconds // microsecond resolution: 01:23:23.123123. assumes Ltime.
Llongfile // full file name and line number: /a/b/c/d.go:23
Lshortfile // final file name element and line number: d.go:23. overrides Llongfile
LUTC // if Ldate or Ltime is set, use UTC rather than the local time zone
Lelapsed // elapsed time since this line was first started
Lisodate
LstdFlags = Ldate | Ltime // initial values for the standard logger
)
type ColorCode int
const (
ColorBlack ColorCode = 30 + iota
ColorRed
ColorGreen
ColorYellow
ColorBlue
ColorMagenta
ColorCyan
ColorWhite
)
const (
ColorNone ColorCode = 0
ColorBold = 1
ColorReset = 39
ColorResetAll = 128
ColorBright = 256
ColorDim = 512
)
func (code ColorCode) GetAnsiCodes() []int {
codes := []int{}
if code&ColorResetAll != 0 {
codes = append(codes, 0)
code = code & (^ColorResetAll)
}
if code&ColorBright != 0 {
codes = append(codes, 1)
code = code & (^ColorBright)
}
if code&ColorDim != 0 {
codes = append(codes, 2)
code = code & (^ColorDim)
}
if code != ColorNone {
codes = append(codes, int(code))
}
return codes
}
var ansiColorCodes = map[string]ColorCode{
"r": ColorResetAll,
"reset": ColorResetAll,
"bold": ColorBold,
"bright": ColorBright,
"dim": ColorBright | ColorBlack,
"black": ColorBlack,
"grey": ColorBlack,
"red": ColorRed,
"green": ColorGreen,
"yellow": ColorYellow,
"blue": ColorBlue,
"magenta": ColorMagenta,
"cyan": ColorCyan,
"white": ColorWhite,
"cr": ColorReset,
"error": ColorRed,
"success": ColorGreen,
"warn": ColorYellow,
}
var tputCache = make(map[string]string)
func tput(strs ...string) string {
key := strings.Join(strs, "-")
val, ok := tputCache[key]
if !ok {
cmd := exec.Command("tput", strs...)
out, err := cmd.Output()
if err != nil {
msg := fmt.Sprintf("\nFailed to execute `tput %s`. That probably means you need to disable MultilineMode.\n", strings.Join(strs, " "))
os.Stderr.WriteString(msg)
return ""
}
val = string(out)
tputCache[key] = val
}
return val
}
type WriterState struct {
mutex sync.Mutex
lastTemp [][]byte
tempLoggers []*Logger
termWidth int
multiline bool
cursorLineIndex int
cursorIsInline bool
cursorIsAtBegin bool
}
func (w *WriterState) removeTempLogger(l *Logger) {
// Remove this logger from the list of tempLoggers for this writer
for i, logger := range w.tempLoggers {
if logger == l {
if i == len(w.tempLoggers)-1 {
w.tempLoggers = w.tempLoggers[:i]
} else {
w.tempLoggers = append(w.tempLoggers[:i], w.tempLoggers[i+1:]...)
}
break
}
}
}
func (w *WriterState) lock() { w.mutex.Lock() }
func (w *WriterState) unlock() { w.mutex.Unlock() }
func (w *WriterState) addTempLogger(l *Logger) {
w.tempLoggers = append(w.tempLoggers, l)
}
func (w *WriterState) flushAll() {
for _, logger := range w.tempLoggers {
logger.flushInt()
}
}
func (w *WriterState) closeAll() {
for _, logger := range w.tempLoggers {
logger.flushInt()
logger.closeInt()
}
}
func getWriterState(writer io.Writer) *WriterState {
mutexGlobal.RLock()
ws, ok := writers[writer]
mutexGlobal.RUnlock()
if !ok {
mutexGlobal.Lock()
ws, ok = writers[writer]
if !ok {
ws = &WriterState{}
ws.cursorIsAtBegin = true
ws.cursorIsInline = false
ws.lastTemp = [][]byte{[]byte{}}
writers[writer] = ws
}
mutexGlobal.Unlock()
}
return ws
}
// ensures atomic writes; shared by all Logger instances
var mutexGlobal sync.RWMutex
var writers map[io.Writer]*WriterState = make(map[io.Writer]*WriterState)
const ansiCodeResetAll = 0
const ansiCodeHighestIntensity = 2
const ansiCodeResetForecolor = 39
var bytesEmpty = []byte("")
var bytesCarriageReturn = []byte("\r")
var byteNewline = byte('\n')
var bytesNewline = []byte{byteNewline}
var bytesSpace = []byte(" ")
var bytesComma = []byte(",")
var ansiColorRegexp = regexp.MustCompile("\033\\[(\\d+(?:;\\d+)*)m")
var ansiColorOrCharRegexp = regexp.MustCompile("(\033\\[\\d+m)|.")
var ansiBytesEscapeStart = []byte("\033[")
var ansiBytesColorEscapeEnd = []byte("m")
var ansiBytesResetAll = []byte("\033[0m")
var ansiBytesResetForecolor = []byte("\033[39m")
var tempLineSep = []byte(" | ")
var tempLineSepLength = VisibleStringLen(tempLineSep)
var tempLineEllipsis = []byte("...")
var tempLineEllipsisLength = VisibleStringLen(tempLineEllipsis)
const minTempSegmentLength = 6
// These facilitate "nullable" bools for some settings
var yes = true
var no = false
func boolPointer(flag bool) *bool {
if flag {
return &yes
}
return &no
}
type ActiveAnsiCodes struct {
intensity int
forecolor int
}
func (codes *ActiveAnsiCodes) anyActive() bool {
return codes.intensity != 0 || codes.forecolor != 0
}
func (codes *ActiveAnsiCodes) add(code int) {
if code == ansiCodeResetAll {
codes.intensity = 0
codes.forecolor = 0
} else if code <= ansiCodeHighestIntensity {
codes.intensity = int(code)
} else if code == ansiCodeResetForecolor {
codes.forecolor = 0
} else {
codes.forecolor = int(code)
}
}
func (codes *ActiveAnsiCodes) getResetBytes() []byte {
if codes.intensity != 0 {
return ansiBytesResetAll
}
if codes.forecolor != 0 {
return ansiBytesResetForecolor
}
return bytesEmpty
}
func getActiveAnsiCodes(buf []byte) *ActiveAnsiCodes {
var ansiActive ActiveAnsiCodes
for _, groups := range ansiColorRegexp.FindAllSubmatch(buf, -1) {
code, _ := strconv.ParseInt(string(groups[1]), 10, 32)
ansiActive.add(int(code))
}
return &ansiActive
}
// A Logger represents an active logging object that generates lines of
// output to an io.Writer. Each logging operation makes a single call to
// the Writer's Write method. A Logger can be used simultaneously from
// multiple goroutines; it guarantees to serialize access to the Writer.
type Logger struct {
prefix []byte // prefix to write at beginning of each line
flag int // properties
out io.Writer // destination for output
buf []byte // for accumulating text to write
tmp []byte // for formatting the current line
prefixFormatted []byte
cursorByteIndex int
tempLineActive bool
isClosed bool
partialLinesEnabled *bool
colorEnabled *bool
colorTemplateEnabled *bool
autoAppendNewline *bool
colorRegexp *regexp.Regexp
termWidth int
callerFile string
callerLine int
now time.Time
lineStartTime time.Time
}
type LoggerInt interface {
Printf(string, ...interface{})
Print(...interface{})
Replacef(string, ...interface{})
Replace(...interface{})
Println(...interface{})
Fatal(...interface{})
Fatalf(string, ...interface{})
Fatalln(...interface{})
Panic(...interface{})
Panicf(string, ...interface{})
Panicln(...interface{})
Bail(error)
BailIf(error)
Flags() int
SetFlags(int)
Prefix() string
SetPrefix(string)
Write([]byte) (int, error)
Colorify(string) string
flushInt()
closeInt()
Flush()
Close() error
SetPartialLinesEnabled(bool)
ShowPartialLines()
HidePartialLines()
SetColorEnabled(bool)
EnableColor()
DisableColor()
SetColorTemplateEnabled(bool)
EnableColorTemplate()
DisableColorTemplate()
SetAutoNewlines(bool)
EnableAutoNewlines()
DisableAutoNewlines()
SetColorTemplateRegexp(*regexp.Regexp)
SetTerminalWidth(int)
SetMultilineEnabled(bool)
EnableMultilineMode()
EnableSinglelineMode()
}
// New creates a new Logger. The out variable sets the
// destination to which log data will be written.
// The prefix appears at the beginning of each generated log line.
// The flag argument defines the logging properties.
func New(out io.Writer, prefix string, flag int) *Logger {
var l = &Logger{out: out, prefix: []byte(prefix), flag: flag}
l.reprocessPrefix()
return l
}
// newStd duplicates some of the work done by New because we can't call
// reprocessPrefix here (as it creates a circular reference back to DefaultLogger)
func newStd() *Logger {
var l = &Logger{out: os.Stderr, prefix: []byte("@(dim:{isodate}) "), flag: 0}
l.partialLinesEnabled = &yes
l.colorRegexp = regexp.MustCompile("@\\(([\\w,]+?)(:([^)]*?))?\\)")
l.colorEnabled = &yes
l.colorTemplateEnabled = &yes
l.autoAppendNewline = &no
// This is like calling reprocessPrefix:
l.prefixFormatted = processColorTemplates(l.colorRegexp, l.prefix)
return l
}
var DefaultLogger = newStd()
func isTrueDefaulted(flag *bool, fallback *bool) bool {
if flag != nil {
return *flag
}
return *fallback
}
func (l *Logger) isColorEnabled() bool {
return isTrueDefaulted(l.colorEnabled, DefaultLogger.colorEnabled)
}
func (l *Logger) isPartialLinesEnabled() bool {
return isTrueDefaulted(l.partialLinesEnabled, DefaultLogger.partialLinesEnabled)
}
func (l *Logger) isAutoNewlineEnabled() bool {
return isTrueDefaulted(l.autoAppendNewline, DefaultLogger.autoAppendNewline)
}
func (l *Logger) getColorTemplateRegexp() *regexp.Regexp {
if !isTrueDefaulted(l.colorTemplateEnabled, DefaultLogger.colorTemplateEnabled) {
return nil
}
if l.colorRegexp != nil {
return l.colorRegexp
}
return DefaultLogger.colorRegexp
}
// SetOutput sets the output destination for the logger.
func (l *Logger) SetOutput(w io.Writer) {
// This is all not really threadsafe. Calling SetOutput while simultaneously writing
// data will result in undefined behavior.
ws := getWriterState(l.out)
ws.lock()
defer ws.unlock()
l.flushInt()
l.out = w
}
// Cheap integer to fixed-width decimal ASCII. Give a negative width to avoid zero-padding.
func itoa(buf *[]byte, i int, wid int) {
// Assemble decimal in reverse order.
var b [20]byte
bp := len(b) - 1
for i >= 10 || wid > 1 {
wid--
q := i / 10
b[bp] = byte('0' + i - q*10)
bp--
i = q
}
// i < 10
b[bp] = byte('0' + i)
*buf = append(*buf, b[bp:]...)
}
func (l *Logger) appendDate(buf *[]byte, useIsoDate bool) {
dateSep := "/"
if useIsoDate {
dateSep = "-"
}
year, month, day := l.now.Date()
itoa(buf, year, 4)
*buf = append(*buf, dateSep...)
itoa(buf, int(month), 2)
*buf = append(*buf, dateSep...)
itoa(buf, day, 2)
}
func (l *Logger) appendTime(buf *[]byte, includeMillis bool, includeMicros bool) {
hour, min, sec := l.now.Clock()
itoa(buf, hour, 2)
*buf = append(*buf, ':')
itoa(buf, min, 2)
*buf = append(*buf, ':')
itoa(buf, sec, 2)
if includeMillis {
*buf = append(*buf, '.')
itoa(buf, l.now.Nanosecond()/1e6, 3)
}
if includeMicros {
*buf = append(*buf, '.')
itoa(buf, l.now.Nanosecond()/1e3, 6)
}
}
func (l *Logger) appendIsoDate(buf *[]byte, includeMillis bool, includeMicros bool) {
l.appendDate(buf, true)
*buf = append(*buf, 'T')
l.appendTime(buf, includeMillis, includeMicros)
}
func (l *Logger) appendElapsed(buf *[]byte) {
if !l.lineStartTime.IsZero() && l.now != l.lineStartTime {
*buf = append(*buf, FormatDuration(l.now.Sub(l.lineStartTime))...)
} else {
*buf = append(*buf, '-')
}
}
var prefixTemplateRegexp = regexp.MustCompile("{(date|time|isodate|elapsed)( millis)?( micros)?}|.+?")
func (l *Logger) formatHeader(buf *[]byte) {
for _, groups := range prefixTemplateRegexp.FindAllSubmatch(l.prefixFormatted, -1) {
if len(groups[1]) != 0 {
s := string(groups[1])
includeMillis := bytes.Equal(groups[2], []byte(" millis"))
includeMicros := bytes.Equal(groups[2], []byte(" micros"))
if s == "date" {
l.appendDate(buf, false)
} else if s == "time" {
l.appendTime(buf, includeMillis, includeMicros)
} else if s == "isodate" {
l.appendIsoDate(buf, includeMillis, includeMicros)
} else if s == "elapsed" {
l.appendElapsed(buf)
}
} else {
*buf = append(*buf, groups[0]...)
}
}
if l.flag&Lisodate != 0 {
l.appendIsoDate(buf, false, l.flag&Lmicroseconds != 0)
*buf = append(*buf, ' ')
} else {
if l.flag&Ldate != 0 {
l.appendDate(buf, false)
*buf = append(*buf, ' ')
}
if l.flag&(Ltime|Lmicroseconds) != 0 {
l.appendTime(buf, false, l.flag&Lmicroseconds != 0)
*buf = append(*buf, ' ')
}
}
if l.flag&(Lshortfile|Llongfile) != 0 {
*buf = append(*buf, l.callerFile...)
*buf = append(*buf, ':')
itoa(buf, l.callerLine, -1)
*buf = append(*buf, ": "...)
}
if l.flag&Lelapsed != 0 && !l.lineStartTime.IsZero() && l.now != l.lineStartTime {
*buf = append(*buf, "("...)
l.appendElapsed(buf)
*buf = append(*buf, ") "...)
}
}
func moveCursorToLine(out io.Writer, line int) bool {
ws := getWriterState(out)
if line == ws.cursorLineIndex {
return false
}
tmp := []byte{}
for line != ws.cursorLineIndex {
if line < ws.cursorLineIndex {
tmp = append(tmp, tput("cuu", "1")...)
ws.cursorLineIndex--
} else {
tmp = append(tmp, tput("cud", "1")...)
ws.cursorLineIndex++
}
}
tmp = append(tmp, bytesCarriageReturn...)
out.Write(tmp)
ws.cursorLineIndex = line
ws.cursorIsAtBegin = true
ws.cursorIsInline = false
return true
}
func setTempLineOutput(out io.Writer, line int, buf []byte) {
ws := getWriterState(out)
cursorIsOnlineAndInline := ws.cursorLineIndex == line && ws.cursorIsInline
lastBuf := ws.lastTemp[line]
// These lengths are actually fine being in bytes
lastLen := len(lastBuf)
currLen := len(buf)
if currLen == lastLen && bytes.Equal(lastBuf, buf) {
// Don't need to do anything
return
} else if cursorIsOnlineAndInline && (currLen >= lastLen && bytes.Equal(lastBuf, buf[:lastLen])) {
out.Write(buf[lastLen:])
} else {
out.Write(getActiveAnsiCodes(lastBuf).getResetBytes())
if !moveCursorToLine(out, line) && !ws.cursorIsAtBegin {
out.Write(bytesCarriageReturn)
}
out.Write(buf)
currStringLen := VisibleStringLen(buf)
lastStringLen := VisibleStringLen(lastBuf)
for i := currStringLen; i < lastStringLen; i++ {
out.Write(bytesSpace)
}
ws.cursorIsInline = currStringLen >= lastStringLen
}
ws.cursorIsAtBegin = false
// This does a lot of copying to avoid aliasing; maybe some could be avoided?
ws.lastTemp[line] = append([]byte{}, buf...)
}
func writeLine(out io.Writer, buf []byte) {
setTempLineOutput(out, 0, buf)
out.Write(getActiveAnsiCodes(buf).getResetBytes())
ws := getWriterState(out)
if ws.multiline {
ws.lastTemp = ws.lastTemp[1:]
// Always keep an empty line at the bottom
if len(ws.lastTemp) == 0 {
ws.lastTemp = append(ws.lastTemp, []byte{})
moveCursorToLine(out, 0)
out.Write(bytesNewline)
} else {
ws.cursorLineIndex = -1
moveCursorToLine(out, 0)
}
} else {
out.Write(bytesNewline)
ws.lastTemp[0] = bytesEmpty
ws.cursorIsAtBegin = true
ws.cursorIsInline = false
}
}
func updateTempOutput(out io.Writer) {
ws := getWriterState(out)
maxWidth := getTermWidth(out) - 1
var bufs [][]byte
for _, logger := range ws.tempLoggers {
bufs = append(bufs, logger.getFormattedLine(logger.buf))
}
if ws.multiline {
for i := len(ws.lastTemp); i < len(bufs); i++ {
moveCursorToLine(out, i-1)
out.Write(bytesNewline)
ws.cursorLineIndex = i
ws.cursorIsAtBegin = true
ws.cursorIsInline = false
ws.lastTemp = append(ws.lastTemp, []byte{})
}
for i, buf := range bufs {
setTempLineOutput(out, i, trimStringEllipsis(buf, maxWidth))
}
} else {
numBufs := len(bufs)
lengths := make([]int, 0)
lengthSum := 0
for _, buf := range bufs {
length := VisibleStringLen(buf)
lengths = append(lengths, length)
lengthSum += length
}
charsLeft := maxWidth - tempLineSepLength*(numBufs-1)
var outputBuf []byte
if len(bufs) > 1 {
if charsLeft < lengthSum {
shortenedLengths := make([]int, numBufs)
copy(shortenedLengths, lengths)
for charsLeft < lengthSum {
longestIndex := 0
longestLength := 0
for i, length := range shortenedLengths {
if length > longestLength {
longestIndex = i
longestLength = length
}
}
if longestLength < minTempSegmentLength {
// Don't bother making segments shorter than this
break
}
if longestLength == lengths[longestIndex] {
// It's at max length; we need to lop off space for the ellipsis
shortenedLengths[longestIndex] -= tempLineEllipsisLength + 1
} else {
shortenedLengths[longestIndex] -= 1
}
lengthSum -= 1
}
var bufs2 [][]byte
for i, buf := range bufs {
if shortenedLengths[i] < lengths[i] {
buf = append(trimString(buf, shortenedLengths[i]), tempLineEllipsis...)
}
bufs2 = append(bufs2, buf)
}
bufs = bufs2
}
}
outputBuf = bytes.Join(bufs, tempLineSep)
outputBuf = trimStringEllipsis(outputBuf, maxWidth)
setTempLineOutput(out, 0, outputBuf)
}
}
func ansiEscapeBytes(colorCode int) []byte {
buf := []byte{}
buf = append(buf, ansiBytesEscapeStart...)
buf = append(buf, fmt.Sprintf("%d", colorCode)...)
buf = append(buf, ansiBytesColorEscapeEnd...)
return buf
}
func Uncolorize(buf []byte) []byte {
return ansiColorRegexp.ReplaceAll(buf, bytesEmpty)
}
func trimString(buf []byte, length int) []byte {
if length == 0 {
return bytesEmpty
}
tmp := []byte{}
for _, groups := range ansiColorOrCharRegexp.FindAllSubmatch(buf, -1) {
tmp = append(tmp, groups[0]...)
if len(groups[1]) == 0 {
// This match was not an ANSI escape, so count it towards the length
length -= 1
if length <= 0 {
return tmp
}
}
}
return tmp
}
func trimStringEllipsis(buf []byte, length int) []byte {
if VisibleStringLen(buf) > length {
return append(trimString(buf, length-tempLineEllipsisLength), tempLineEllipsis...)
}
return buf
}
func VisibleStringLen(buf []byte) int {
return utf8.RuneCount(Uncolorize(buf))
}
func (l *Logger) getFormattedLine(line []byte) []byte {
l.tmp = l.tmp[:0]
l.formatHeader(&l.tmp)
codes := getActiveAnsiCodes(l.tmp)
l.tmp = append(l.tmp, codes.getResetBytes()...)
l.tmp = append(l.tmp, line...)
if !l.isColorEnabled() {
l.tmp = Uncolorize(l.tmp)
}
return l.tmp
}
func (l *Logger) reprocessPrefix() {
colorTemplateRegexp := l.getColorTemplateRegexp()
if colorTemplateRegexp != nil {
l.prefixFormatted = processColorTemplates(colorTemplateRegexp, l.prefix)
} else {
l.prefixFormatted = l.prefix
}
}
func processColorTemplates(colorTemplateRegexp *regexp.Regexp, buf []byte) []byte {
// We really want ReplaceAllSubmatchFunc, i.e.: https://github.com/golang/go/issues/5690
// Instead we call FindSubmatch on each match, which means that backtracking may not be
// used in custom Regexps (matches must also match on themselves without context).
colorTemplateReplacer := func(token []byte) []byte {
tmp2 := []byte{}
groups := colorTemplateRegexp.FindSubmatch(token)
var ansiActive ActiveAnsiCodes
for _, codeBytes := range bytes.Split(groups[1], bytesComma) {
colorCode, ok := ansiColorCodes[string(codeBytes)]
if !ok {
// Don't modify the text if we don't recognize any of the codes
return groups[0]
}
for _, code := range colorCode.GetAnsiCodes() {
ansiActive.add(code)
tmp2 = append(tmp2, ansiEscapeBytes(code)...)
}
}
if len(groups[2]) > 0 {
tmp2 = append(tmp2, groups[3]...)
tmp2 = append(tmp2, ansiActive.getResetBytes()...)
}
return tmp2
}
return colorTemplateRegexp.ReplaceAllFunc(buf, colorTemplateReplacer)
}
func (l *Logger) applyColorTemplates(s string) string {
colorTemplateRegexp := l.getColorTemplateRegexp()
if colorTemplateRegexp != nil {
return string(processColorTemplates(colorTemplateRegexp, []byte(s)))
} else {
return s
}
}
func (l *Logger) injectAtVirtualCursor(input []byte) {
if len(l.buf) != l.cursorByteIndex {
// Append s to l.buf[:cursorByteIndex], consuming l.buf[cursorByteIndex:] with
// each rune, but also injecting ansi escapes at the new old/new transition
// column to keep the colors consistent.
if l.cursorByteIndex > len(l.buf) || l.cursorByteIndex < 0 {
panic(fmt.Sprintf("injectAtVirtualCursor will fail with cursorByteIndex=%d and len(buf)=%d", l.cursorByteIndex, len(l.buf)))
}
defer func() {
if e := recover(); e != nil {
panic(fmt.Sprintf("injectAtVirtualCursor failed with cursorByteIndex=%d and len(buf)=%d. Original: %v", l.cursorByteIndex, len(l.buf), e))
}
}()
before := l.buf[:l.cursorByteIndex]
after := l.buf[l.cursorByteIndex:]
afterLength := VisibleStringLen(after)
inputLength := VisibleStringLen(input)
if inputLength >= afterLength {
// We're removing all the after text, so no need to compare colors
// and/or inject any escapes to heal the after text.
l.buf = append(before, input...)
l.cursorByteIndex += len(input)
} else {
removed := trimString(after, inputLength)
ansiOld := getActiveAnsiCodes(append(before, removed...))
ansiNew := getActiveAnsiCodes(append(before, input...))
escapes := []byte{}
changedIntensity := ansiNew.intensity != ansiOld.intensity
changedForecolor := ansiNew.forecolor != ansiOld.forecolor
if changedIntensity {
escapes = append(escapes, ansiBytesResetAll...)
} else if changedForecolor {
escapes = append(escapes, ansiBytesResetForecolor...)
}
if changedIntensity && ansiOld.intensity != 0 {
escapes = append(escapes, ansiEscapeBytes(ansiOld.intensity)...)
}
if (changedIntensity || changedForecolor) && ansiOld.forecolor != 0 {
escapes = append(escapes, ansiEscapeBytes(ansiOld.forecolor)...)
}
afterKept := append(escapes, after[len(removed):]...)
l.buf = append(before, input...)
l.cursorByteIndex += len(input)
l.buf = append(l.buf, afterKept...) // Don't advance cursor for this part
}
} else {
l.buf = append(l.buf, input...)
l.cursorByteIndex += len(input)
}
}
func (l *Logger) Output(calldepth int, _s string) error {
return l.intOutput(calldepth+1, []byte(_s), false)
}
// Output writes the output for a logging event. The string s contains
// the text to print after the prefix specified by the flags of the
// Logger. A newline is appended if the last character of s is not
// already a newline. Calldepth is used to recover the PC and is
// provided for generality, although at the moment on all pre-defined
// paths it will be 2.
func (l *Logger) intOutput(calldepth int, s []byte, haveLock bool) error {
ws := getWriterState(l.out)
if !haveLock {
ws.lock()
defer ws.unlock()
}
l.now = time.Now() // get this early.
if l.flag&LUTC != 0 {
l.now = l.now.UTC()
}
if l.isClosed {
return errors.New("Attempted to write to closed Logger.")
}
// This is kind of kludgy, but better than nothing:
s = []byte(strings.Replace(string(s), "\t", " ", -1))
if l.isAutoNewlineEnabled() && len(s) > 0 && s[len(s)-1] != byteNewline {
s = append(s, byteNewline)
}
l.injectAtVirtualCursor(s)
wroteFullLine := false
for true {
indexNewline := bytes.IndexByte(l.buf, '\n')
var currLine []byte
if indexNewline == -1 {
currLine = l.buf
} else {
currLine = l.buf[:indexNewline]
}
indexCr := bytes.IndexByte(currLine, '\r')
// Kludge: ignore carriage return just before newline:
if indexCr != -1 && indexCr != indexNewline-1 {
// For every carriage return found within the current line, detach the text
// after the carriage return and inject at the beginning of the line.
after := l.buf[indexCr+1:]
l.buf = l.buf[:indexCr]
l.cursorByteIndex = 0
l.injectAtVirtualCursor(after)
continue
}
if indexNewline == -1 {
break
}
l.buf = l.buf[indexNewline+1:]
l.cursorByteIndex = 0
if l.flag&(Lshortfile|Llongfile) != 0 && len(l.callerFile) == 0 {
// release lock while getting caller info - it's expensive.
if !haveLock {
ws.unlock()
}
var ok bool
_, l.callerFile, l.callerLine, ok = runtime.Caller(calldepth)
if !ok {
l.callerFile = "???"
l.callerLine = 0
}
if l.flag&Lshortfile != 0 {
for i := len(l.callerFile) - 1; i > 0; i-- {
if l.callerFile[i] == '/' {
l.callerFile = l.callerFile[i+1:]
break
}
}
}
if !haveLock {
ws.lock()
}
}
// ansiActive := getActiveAnsiCodes(currLine)
ws.removeTempLogger(l)
l.tempLineActive = false
writeLine(l.out, l.getFormattedLine(currLine))
wroteFullLine = true
// // XXX This is probably inefficient?:
// prepends := []byte{}
// if ansiActive.intensity != 0 {
// prepends = append(prepends, ansiEscapeBytes(ansiActive.intensity)...)
// }
// if ansiActive.forecolor != 0 {
// prepends = append(prepends, ansiEscapeBytes(ansiActive.forecolor)...)
// }
// if len(prepends) > 0 {
// l.buf = append(prepends, l.buf...)
// l.cursorByteIndex += len(prepends)
// }
}
if wroteFullLine {
l.callerFile = ""
l.callerLine = 0
}
if !l.tempLineActive && l.isPartialLinesEnabled() && VisibleStringLen(l.buf) > 0 {
ws.addTempLogger(l)
l.tempLineActive = true
l.lineStartTime = l.now
}
updateTempOutput(l.out)
return nil
}
func (l *Logger) truncateBuf() {
l.buf = l.buf[:0]
l.cursorByteIndex = 0
}
// Printf calls l.Output to print to the logger.
// Arguments are handled in the manner of fmt.Printf.
func (l *Logger) Printf(format string, v ...interface{}) {
ws := getWriterState(l.out)
ws.lock()
defer ws.unlock()
l.intOutput(2, []byte(fmt.Sprintf(l.applyColorTemplates(format), v...)), true)
}
// Print calls l.Output to print to the logger.
// Arguments are handled in the manner of fmt.Print.
func (l *Logger) Print(v ...interface{}) { l.intOutput(2, []byte(fmt.Sprint(v...)), false) }
// Log calls l.Output to print to the logger, adding a newline at the end of the format string.
// Arguments are handled in the manner of fmt.Printf.
func (l *Logger) Log(format string, v ...interface{}) {
l.Printf(format+"\n", v...)
}
// Info is a synomym for Log
func (l *Logger) Info(format string, v ...interface{}) {
l.Log(format, v...)
}
func (l *Logger) Replacef(format string, v ...interface{}) {
ws := getWriterState(l.out)
ws.lock()
defer ws.unlock()
l.truncateBuf()
l.intOutput(2, []byte(fmt.Sprintf(l.applyColorTemplates(format), v...)), true)
}
func (l *Logger) Replace(v ...interface{}) {
ws := getWriterState(l.out)
ws.lock()
defer ws.unlock()
l.truncateBuf()
l.intOutput(2, []byte(fmt.Sprint(v...)), true)
}
// Println calls l.intOutput to print to the logger.
// Arguments are handled in the manner of fmt.Println.
func (l *Logger) Println(v ...interface{}) { l.intOutput(2, []byte(fmt.Sprintln(v...)), false) }
func (l *Logger) Error(format string, v ...interface{}) {
if !strings.HasSuffix(format, "\n") {
format += "\n"
}
l.Printf(format, v...)
}
// Fatal is equivalent to l.Print() followed by a call to os.Exit(1).
func (l *Logger) Fatal(v ...interface{}) {
l.intOutput(2, []byte(fmt.Sprint(v...)), false)
osExit()
}
// Fatalf is equivalent to l.Printf() followed by a call to os.Exit(1).