-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogcrunch.go
More file actions
56 lines (49 loc) · 1.24 KB
/
logcrunch.go
File metadata and controls
56 lines (49 loc) · 1.24 KB
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
package tok
import (
"fmt"
"regexp"
"strings"
)
var logLineRe = regexp.MustCompile(`(?i)(?:^[0-9\[\]\s\-T:.Z]{0,35})?\b(INFO|DEBUG|WARN|WARNING|ERROR|FATAL|TRACE)\b`)
func logLevel(line string) string {
m := logLineRe.FindStringSubmatch(line)
if m == nil {
return ""
}
return strings.ToUpper(m[1])
}
func isHighPriority(level string) bool {
return level == "ERROR" || level == "WARN" || level == "WARNING" || level == "FATAL"
}
// CompressLog preserves ERROR/WARN/FATAL lines and stack traces,
// collapsing runs of 3+ similar INFO/DEBUG lines into a summary.
func CompressLog(text string) string {
lines := strings.Split(text, "\n")
var out []string
var run []string
flushRun := func() {
if len(run) < 3 {
out = append(out, run...)
} else {
out = append(out, run[0])
out = append(out, fmt.Sprintf("[%d similar lines collapsed]", len(run)-2))
out = append(out, run[len(run)-1])
}
run = nil
}
for _, line := range lines {
level := logLevel(line)
if level == "" || isHighPriority(level) {
flushRun()
out = append(out, line)
continue
}
// INFO/DEBUG/TRACE — accumulate run
if len(run) > 0 && logLevel(run[0]) != level {
flushRun()
}
run = append(run, line)
}
flushRun()
return strings.Join(out, "\n")
}