-
Notifications
You must be signed in to change notification settings - Fork 0
/
checkLog.go
136 lines (111 loc) · 2.43 KB
/
checkLog.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
package main
import (
"log"
"os"
"strconv"
"strings"
"time"
"github.com/infrasonar/go-libagent"
)
type LogHelper struct {
layout string
lsz int
fn string
sz int
}
var lh *LogHelper
func InitLogHelper() {
layout := os.Getenv("LOG_DATE_FMT")
if layout == "" {
layout = "01/02/2006 15:04:05.999999"
}
lsz := len(layout)
_, err := time.Parse(layout, layout)
if err != nil {
log.Fatal(err)
}
fn := os.Getenv("LOG_FILE_PATH")
if fn == "" {
fn = "/opt/QStar/log/syslog"
}
szs := os.Getenv("LOG_BUF_SIZE")
if szs == "" {
szs = "8192"
}
sz, err := strconv.Atoi(szs)
if err != nil {
log.Fatal(err)
} else if sz <= 0 {
log.Fatal("Invalid LOG_BUF_SIZE")
}
lh = &LogHelper{
layout: layout,
lsz: lsz,
fn: fn,
sz: sz,
}
}
func CheckLog(_ *libagent.Check) (map[string][]map[string]any, error) {
state := map[string][]map[string]any{}
file, err := os.Open(lh.fn)
if err != nil {
return nil, err
}
defer file.Close()
buf := make([]byte, lh.sz)
stat, statErr := file.Stat()
if statErr != nil {
panic(statErr)
}
start := stat.Size() - int64(lh.sz)
if start < 0 {
start = 0
}
_, err = file.ReadAt(buf, start)
if err != nil {
return nil, err
}
var parseError error
var item map[string]any = nil
prevName := ""
items := []map[string]any{}
logStr := string(buf[:])
lines := strings.Split(strings.ReplaceAll(logStr, "\r\n", "\n"), "\n")
for i, line := range lines {
if (start != 0 && i == 0) || len(line) <= lh.lsz {
continue // Ignore fist line if start is not the begin
}
dtstr := line[:lh.lsz]
message := strings.TrimSpace(line[lh.lsz:])
dt, err := time.Parse(lh.layout, dtstr)
if err != nil {
if item == nil {
if parseError == nil {
log.Printf("Failed to read date from line %v (line: %v, layout: %v)\n", i, dtstr, lh.layout)
}
parseError = err
} else {
item["message"] = item["message"].(string) + "\n" + message
}
continue // Ignote lines with errors
}
name := strconv.FormatInt(dt.UnixNano(), 10)
timestamp := float64(dt.UnixMilli()) / 1000.0
if name == prevName {
continue // Duplicate name
}
prevName = name
item = map[string]any{
"name": name,
"timestamp": timestamp,
"datestr": dtstr,
"message": message,
}
items = append(items, item)
}
state["log"] = items
// Print debug dump
// b, _ := json.MarshalIndent(state, "", " ")
// log.Fatal(string(b))
return state, parseError
}