-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
116 lines (102 loc) · 2.05 KB
/
main.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
package main
import (
"log"
"path/filepath"
"os"
"io/ioutil"
"sync"
"github.com/joho/godotenv"
"github.com/fsnotify/fsnotify"
)
type ArkNotifier struct {
sync.Mutex
LogDir string
LogSizeTable map[string]int64
WebhookURL string
}
func (an *ArkNotifier) Initialize() {
an.LogDir = os.Getenv("ARK_LOG_DIR")
an.LogSizeTable = make(map[string]int64)
an.WebhookURL = os.Getenv("DISCORD_WEBHOOK_URL")
files, err := filepath.Glob(an.LogDir + "*.log")
if err != nil {
panic(err)
}
for _, f := range files {
stat, err := os.Stat(f)
if err != nil {
continue
}
log.Println(f, stat.Size())
an.LogSizeTable[f] = stat.Size()
}
}
func (an *ArkNotifier) onLogFileUpdated(path string){
log.Println("modified file:", path)
fp, err := os.Open(path)
if err != nil {
log.Println("error while open:", err)
return
}
defer fp.Close()
an.Lock()
defer an.Unlock()
fp.Seek(an.LogSizeTable[path], 0)
logs, err := ioutil.ReadAll(fp)
if err != nil {
log.Println("error while ReadAll:", err)
return
}
logLine := string(logs)
log.Printf("read %d bytes: %s", len(logs), logLine)
an.LogSizeTable[path] += int64(len(logs))
event, err := ParseEventFromLogLine(logLine)
if err != nil {
log.Printf("error while parsing logline: %s", err.Error());
return
}
log.Printf("%#v\n", event)
an.NotifyEvent(event)
}
func (an *ArkNotifier) Watch(){
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
done := make(chan bool)
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
log.Println("event:", event)
if event.Op&fsnotify.Write == fsnotify.Write {
fileName := event.Name
an.onLogFileUpdated(fileName)
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Println("error:", err)
}
}
}()
err = watcher.Add(an.LogDir)
if err != nil {
log.Fatal(err)
}
<-done
}
func main() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
var an ArkNotifier
an.Initialize()
an.Watch()
}