-
Notifications
You must be signed in to change notification settings - Fork 1
/
example_test.go
56 lines (52 loc) · 1.21 KB
/
example_test.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
package follow_test
import (
"fmt"
"io"
"os"
"path/filepath"
"time"
"github.com/kei2100/follow"
"github.com/kei2100/follow/posfile"
)
func ExampleReader() {
dir, _ := os.MkdirTemp("", "ExampleReader")
logpath := filepath.Join(dir, "test.log")
logfile, _ := os.Create(logpath)
// Create follow.Reader.
// follow.Reader is a file Reader that behaves like `tail -F`
opts := []follow.OptionFunc{
follow.WithPositionFile(posfile.InMemory(nil, 0)),
follow.WithRotatedFilePathPatterns([]string{filepath.Join(dir, "test.log.*")}),
follow.WithDetectRotateDelay(0),
follow.WithWatchRotateInterval(100 * time.Millisecond),
}
reader, _ := follow.Open(logpath, opts...)
defer reader.Close()
// Reads log files while tracking their rotation
go func() {
for {
b, _ := io.ReadAll(reader)
if len(b) > 0 {
fmt.Print(string(b))
}
time.Sleep(100 * time.Millisecond)
}
}()
// Write to logfile
fmt.Fprintln(logfile, "1")
fmt.Fprintln(logfile, "2")
// Rotate logfile
logfile.Close()
os.Rename(logpath, logpath+".1")
logfile, _ = os.Create(logpath)
// Write to new logfile
fmt.Fprintln(logfile, "3")
fmt.Fprintln(logfile, "4")
logfile.Close()
time.Sleep(time.Second)
// Output:
// 1
// 2
// 3
// 4
}