@@ -2,7 +2,7 @@ package follow_test
2
2
3
3
import (
4
4
"fmt"
5
- "io/ioutil "
5
+ "io"
6
6
"os"
7
7
"path/filepath"
8
8
"time"
@@ -12,55 +12,45 @@ import (
12
12
)
13
13
14
14
func ExampleReader () {
15
- dir , _ := ioutil .TempDir ("" , "follow-test" )
16
- path := filepath .Join (dir , "test.log" )
17
- f1 , _ := os .Create (path )
18
-
19
- // create follow.Reader.
15
+ dir , _ := os .MkdirTemp ("" , "ExampleReader" )
16
+ logpath := filepath .Join (dir , "test.log" )
17
+ logfile , _ := os .Create (logpath )
18
+ // Create follow.Reader.
20
19
// follow.Reader is a file Reader that behaves like `tail -F`
21
- options := []follow.OptionFunc {
22
- // position-file supported
20
+ opts := []follow.OptionFunc {
23
21
follow .WithPositionFile (posfile .InMemory (nil , 0 )),
24
- follow .WithRotatedFilePathPatterns ([]string {filepath .Join (dir , "* .log.*" )}),
22
+ follow .WithRotatedFilePathPatterns ([]string {filepath .Join (dir , "test .log.*" )}),
25
23
follow .WithDetectRotateDelay (0 ),
26
24
follow .WithWatchRotateInterval (100 * time .Millisecond ),
27
25
}
28
- reader , _ := follow .Open (path , options ... )
29
-
30
- f1 .WriteString ("1" )
31
- b , _ := ioutil .ReadAll (reader )
32
- fmt .Printf ("%s\n " , b )
33
-
34
- // rotate
35
- f1 .Close ()
36
- os .Rename (path , path + ".f1" )
37
- f2 , _ := os .Create (path )
38
-
39
- f2 .WriteString ("2" )
40
- time .Sleep (500 * time .Millisecond ) // wait for detect rotate
41
- b , _ = ioutil .ReadAll (reader )
42
- fmt .Printf ("%s\n " , b )
43
-
44
- // write and rotate while closing the follow.Reader
45
- reader .Close ()
46
- f2 .WriteString ("3" )
47
- f2 .Close ()
48
-
49
- os .Rename (path , path + ".f2" )
50
- f3 , _ := os .Create (path )
51
- defer f3 .Close ()
52
- f3 .WriteString ("4" )
53
-
54
- // re-open follow.Reader
55
- reader , _ = follow .Open (path , options ... )
26
+ reader , _ := follow .Open (logpath , opts ... )
56
27
defer reader .Close ()
57
-
58
- time .Sleep (500 * time .Millisecond ) // wait for detect rotate
59
- b , _ = ioutil .ReadAll (reader )
60
- fmt .Printf ("%s\n " , b )
28
+ // Reads log files while tracking their rotation
29
+ go func () {
30
+ for {
31
+ b , _ := io .ReadAll (reader )
32
+ if len (b ) > 0 {
33
+ fmt .Print (string (b ))
34
+ }
35
+ time .Sleep (100 * time .Millisecond )
36
+ }
37
+ }()
38
+ // Write to logfile
39
+ fmt .Fprintln (logfile , "1" )
40
+ fmt .Fprintln (logfile , "2" )
41
+ // Rotate logfile
42
+ logfile .Close ()
43
+ os .Rename (logpath , logpath + ".1" )
44
+ logfile , _ = os .Create (logpath )
45
+ // Write to new logfile
46
+ fmt .Fprintln (logfile , "3" )
47
+ fmt .Fprintln (logfile , "4" )
48
+ logfile .Close ()
49
+ time .Sleep (time .Second )
61
50
62
51
// Output:
63
52
// 1
64
53
// 2
65
- // 34
54
+ // 3
55
+ // 4
66
56
}
0 commit comments