/
tail_utils.go
118 lines (94 loc) · 2.39 KB
/
tail_utils.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
package stern
import (
"errors"
"regexp"
"sort"
"strings"
"time"
"github.com/fatih/color"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// Log is the object which will be used together with the template to generate
// the output.
type Log struct {
// Message is the log message itself
Message string `json:"message"`
// Node name of the pod
NodeName string `json:"nodeName"`
// Namespace of the pod
Namespace string `json:"namespace"`
// PodName of the pod
PodName string `json:"podName"`
// ContainerName of the container
ContainerName string `json:"containerName"`
PodColor *color.Color `json:"-"`
ContainerColor *color.Color `json:"-"`
}
type TailOptions struct {
Timestamps bool
TimestampFormat string
Location *time.Location
SinceSeconds *int64
SinceTime *metav1.Time
Exclude []*regexp.Regexp
Include []*regexp.Regexp
Highlight []*regexp.Regexp
Namespace bool
TailLines *int64
Follow bool
OnlyLogLines bool
// regexp for highlighting the matched string
reHightlight *regexp.Regexp
}
func (o TailOptions) IsExclude(msg string) bool {
for _, rex := range o.Exclude {
if rex.MatchString(msg) {
return true
}
}
return false
}
func (o TailOptions) IsInclude(msg string) bool {
if len(o.Include) == 0 {
return true
}
for _, rin := range o.Include {
if rin.MatchString(msg) {
return true
}
}
return false
}
var colorHighlight = color.New(color.FgRed, color.Bold).SprintFunc()
func (o TailOptions) HighlightMatchedString(msg string) string {
highlight := append(o.Include, o.Highlight...)
if len(highlight) == 0 {
return msg
}
if o.reHightlight == nil {
ss := make([]string, len(highlight))
for i, hl := range highlight {
ss[i] = hl.String()
}
// We expect a longer match
sort.Slice(ss, func(i, j int) bool {
return len(ss[i]) > len(ss[j])
})
o.reHightlight = regexp.MustCompile("(" + strings.Join(ss, "|") + ")")
}
msg = o.reHightlight.ReplaceAllStringFunc(msg, func(part string) string {
return colorHighlight(part)
})
return msg
}
func (o TailOptions) UpdateTimezoneAndFormat(timestamp string) (string, error) {
t, err := time.ParseInLocation(time.RFC3339Nano, timestamp, time.UTC)
if err != nil {
return "", errors.New("missing timestamp")
}
format := TimestampFormatDefault
if o.TimestampFormat != "" {
format = o.TimestampFormat
}
return t.In(o.Location).Format(format), nil
}