This repository has been archived by the owner on Dec 20, 2019. It is now read-only.
forked from bakins/kube-log-tail
-
Notifications
You must be signed in to change notification settings - Fork 0
/
color.go
88 lines (74 loc) · 1.61 KB
/
color.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
package kubelogtail
import (
"fmt"
"sync"
"github.com/fatih/color"
"github.com/pkg/errors"
)
// color mode
const (
logColorLine = iota // whole line - the default
logColorPod // just the pod
logColorOff // no color
)
type colorFunc func(string, string)
type logColorPrint struct {
sync.Mutex
colorFuncs []colorFunc
currentColor int //index of current color
mode int
}
func newLogColorPrint(mode string) (*logColorPrint, error) {
m := logColorLine
switch mode {
case "off":
m = logColorOff
case "pod":
m = logColorPod
case "line", "":
m = logColorLine
default:
return nil, errors.Errorf("unknown color print mode: \"%s\"", mode)
}
l := logColorPrint{
mode: m,
}
l.generateColors()
return &l, nil
}
type fmtPrinter func(format string, a ...interface{}) string
func (l *logColorPrint) generateColors() {
l.Lock()
defer l.Unlock()
if l.mode == logColorOff {
f := func(label, line string) {
fmt.Println(label, line)
}
l.colorFuncs = []colorFunc{f}
return
}
colors := []fmtPrinter{color.BlueString, color.CyanString, color.YellowString, color.RedString, color.MagentaString}
for i := range colors {
f := colors[i]
var cf colorFunc
if l.mode == logColorPod {
cf = func(label, line string) {
fmt.Println(f(label), line)
}
} else {
cf = func(label, line string) {
f("%s %s\n", label, line)
}
}
l.colorFuncs = append(l.colorFuncs, cf)
}
}
func (l *logColorPrint) getColor() colorFunc {
l.Lock()
defer l.Unlock()
l.currentColor++
if l.currentColor >= len(l.colorFuncs) {
l.currentColor = 0
}
return l.colorFuncs[l.currentColor]
}