-
Notifications
You must be signed in to change notification settings - Fork 2
/
tail.go
76 lines (64 loc) · 1.46 KB
/
tail.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
package tail
import (
"fmt"
"io"
"io/ioutil"
"log"
"os"
"strings"
"github.com/fsnotify/fsnotify"
"github.com/kaz/flos/libra"
"github.com/kaz/flos/state"
)
var (
logger = log.New(os.Stdout, "[tail] ", log.Ltime)
// now concurrent read only
files = map[string]*os.File{}
)
func StartWorker() {
tailer, err := fsnotify.NewWatcher()
if err != nil {
logger.Printf("failed to init watcher: %v\n", err)
return
}
defer tailer.Close()
for _, path := range state.Get().Tail {
file, err := os.Open(path)
if err != nil {
logger.Printf("failed to open file: %v\n", err)
continue
}
if _, err := file.Seek(0, io.SeekEnd); err != nil {
logger.Printf("failed to seek file: %v\n", err)
continue
}
files[path] = file
if err := tailer.Add(path); err != nil {
logger.Printf("failed to watch: %v\n", err)
continue
}
logger.Printf("Watching file=%v\n", path)
}
for ev := range tailer.Events {
go eventProcess(&ev)
}
}
func eventProcess(ev *fsnotify.Event) {
if ev.Op&fsnotify.Write != 0 {
file, ok := files[ev.Name]
if !ok {
logger.Printf("event for unexpected file=%v detected\n", ev.Name)
return
}
data, err := ioutil.ReadAll(file)
if err != nil {
logger.Printf("failed to read file: %v\n", err)
return
}
if _, err := file.Seek(0, io.SeekEnd); err != nil {
logger.Printf("failed to seek file: %v\n", err)
return
}
libra.Put("tail", fmt.Sprintf("[%v] %v", ev.Name, strings.Trim(string(data), "\r\n")))
}
}