-
Notifications
You must be signed in to change notification settings - Fork 7
/
tail.go
48 lines (43 loc) · 960 Bytes
/
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
package main
import (
"fmt"
"log"
"os"
"github.com/hpcloud/tail"
"golang.org/x/net/context"
)
func tailFile(ctx context.Context, cancel context.CancelFunc, fileName string, poll bool, dest *os.File) {
defer wg.Done()
// Make sure we can read it -- apparently tail.TailFile does not complain if the file does not exist!!
_file, err := os.Open(fileName)
if err != nil {
log.Printf("Error opening '%s':%s\n", fileName, err)
cancel()
}
_file.Close()
t, err := tail.TailFile(fileName, tail.Config{
Follow: true,
ReOpen: true,
Poll: poll,
Logger: tail.DiscardingLogger,
})
if err != nil {
log.Printf("unable to tail %s: %s\n", fileName, err)
cancel()
}
// main loop
for {
select {
// if the channel is done, then exit the loop
case <-ctx.Done():
t.Stop()
t.Cleanup()
return
// get the next log line and echo it out
case line := <-t.Lines:
if line != nil {
fmt.Fprintln(dest, line.Text)
}
}
}
}