-
Notifications
You must be signed in to change notification settings - Fork 415
/
tail.go
67 lines (59 loc) · 1.26 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
package main
import (
"fmt"
"log"
"os"
"time"
"github.com/hpcloud/tail"
"golang.org/x/net/context"
)
func tailFile(ctx context.Context, file string, poll bool, dest *os.File) {
defer wg.Done()
var isPipe bool
var errCount int
s, err := os.Stat(file)
if err != nil {
log.Printf("Warning: unable to stat %s: %s", file, err)
errCount++
isPipe = false
} else {
isPipe = s.Mode()&os.ModeNamedPipe != 0
}
t, err := tail.TailFile(file, tail.Config{
Follow: true,
ReOpen: true,
Poll: poll,
Logger: tail.DiscardingLogger,
Pipe: isPipe,
})
if err != nil {
log.Fatalf("unable to tail %s: %s", file, err)
}
defer func() {
t.Stop()
t.Cleanup()
}()
// main loop
for {
select {
// if the channel is done, then exit the loop
case <-ctx.Done():
return
// get the next log line and echo it out
case line := <-t.Lines:
if t.Err() != nil {
log.Printf("Warning: unable to tail %s: %s", file, t.Err())
errCount++
if errCount > 30 {
log.Fatalf("Logged %d consecutive errors while tailing. Exiting", errCount)
}
time.Sleep(2 * time.Second) // Sleep for 2 seconds before retrying
} else if line == nil {
return
} else {
fmt.Fprintln(dest, line.Text)
errCount = 0 // Zero the error count
}
}
}
}