-
Notifications
You must be signed in to change notification settings - Fork 1
/
watch.go
104 lines (92 loc) · 2.42 KB
/
watch.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
// Copyright 2023 The Yock Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package log
import (
"fmt"
"path/filepath"
"regexp"
"strings"
"github.com/ansurfen/yock/util"
)
var DefaultLoggerWatch *LoggerWatch
const LoggerFormat = "(.*)(\033\\[\\d+m)+(INFO|DEBUG|FATAL|WARN|PANIC|ERROR)(\033\\[0m)+(.*)"
type LoggerWatch struct {
loggerEntries map[string][]*loggerEntry
}
func New() *LoggerWatch {
return &LoggerWatch{
loggerEntries: make(map[string][]*loggerEntry),
}
}
func (lw *LoggerWatch) Find(file, time, level, caller, msg string) (ret []*loggerEntry) {
for name, entries := range lw.loggerEntries {
if file != "*" && !strings.Contains(name, file) {
continue
}
for _, entry := range entries {
if time != "*" && !strings.Contains(entry.Time, time) {
continue
}
if level != "*" && !strings.Contains(entry.Level, level) {
continue
}
if caller != "*" && !strings.Contains(entry.Caller, caller) {
continue
}
if msg != "*" && !strings.Contains(entry.Msg, msg) {
continue
}
if !entry.isTrim {
entry.isTrim = true
entry.trim()
}
ret = append(ret, entry)
}
}
return
}
func (lw *LoggerWatch) Parse(path string) error {
re := regexp.MustCompile(LoggerFormat)
fmt.Println(path)
if filepath.Ext(path) == ".log" {
lw.loggerEntries[path] = []*loggerEntry{}
util.ReadLineFromFile(path, func(s string) string {
s = strings.TrimSpace(s)
if len(s) == 0 {
return ""
}
if re.MatchString(s) {
res := re.FindStringSubmatch(s)
lw.loggerEntries[path] = append(lw.loggerEntries[path], &loggerEntry{
Time: strings.TrimSpace(res[1]),
Level: strings.TrimSpace(res[3]),
Msg: strings.TrimLeft(res[5], " "),
})
} else {
n := len(lw.loggerEntries[path]) - 1
lw.loggerEntries[path][n].Msg += "\n" + s
}
return ""
})
}
return nil
}
type loggerEntry struct {
Time string `json:"time"`
Level string `json:"level"`
Caller string `json:"caller"`
Msg string `json:"msg"`
isTrim bool `json:"-"`
}
var extract = regexp.MustCompile(`(.*:\d+)`)
func (entry *loggerEntry) trim() {
if extract.MatchString(entry.Msg) {
if loc := extract.FindStringIndex(entry.Msg); len(loc) > 1 {
entry.Caller = strings.TrimSpace(entry.Msg[:loc[1]])
entry.Msg = strings.TrimSpace(entry.Msg[loc[1]:])
}
} else {
entry.Msg = strings.TrimSpace(entry.Msg)
}
}