-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
80 lines (69 loc) · 1.28 KB
/
logger.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
package logger
import (
"log"
"path/filepath"
"github.com/fsnotify/fsnotify"
)
var watcher *fsnotify.Watcher
var watchedFiles map[string]*File
//
// Change struct holds information about *NEW* changes in a logfile.
//
type Change struct {
Event string
File *File
Lines []*Line
}
//
// Start the logger. New changes in the given files will return on the given channel.
//
func Start(result chan *Change, files ...string) error {
var err error
watcher, err = fsnotify.NewWatcher()
if err != nil {
return err
}
defer func() {
derr := watcher.Close()
if derr != nil {
log.Println(derr)
}
}()
errCh := make(chan error)
watchedFiles = make(map[string]*File)
go func() {
for {
select {
case event := <-watcher.Events:
change, err := (watchedFiles[event.Name]).HandleEvent(event.Op)
if err != nil {
errCh <- err
}
result <- change
case err := <-watcher.Errors:
errCh <- err
}
}
}()
for _, path := range files {
path = filepath.Clean(path)
lf, err := NewFile(path)
if err != nil {
return err
}
err = watcher.Add(path)
if err != nil {
return err
}
lines, err := lf.Parse()
if err != nil {
return err
}
result <- &Change{
File: &lf,
Lines: lines,
}
watchedFiles[path] = &lf
}
return <-errCh
}