-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
73 lines (61 loc) · 1.73 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package rotate_test
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"time"
"github.com/kei2100/rotate"
)
func ExampleWriter() {
dir, err := ioutil.TempDir("", "rotate-test")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
const bytes3 int64 = 3
w, err := rotate.NewWriter(dir, "test.log", rotate.WithSizeBasedPolicy(bytes3))
if err != nil {
panic(err)
}
defer w.Close()
fmt.Fprint(w, "1")
fmt.Fprint(w, "2")
fmt.Fprint(w, "3")
time.Sleep(time.Second) // wait for rotate
fmt.Fprint(w, "4")
b0, _ := ioutil.ReadFile(filepath.Join(dir, "test.log"))
b1, _ := ioutil.ReadFile(filepath.Join(dir, "test.log.1"))
fmt.Printf("%s/%s", b0, b1)
// Output: 4/123
}
func ExampleWriter_timeBased() {
dir, err := ioutil.TempDir("", "rotate-test")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
w, err := rotate.NewWriter(dir, "test.log", rotate.WithTimeBasedPolicy(func(openedAtUnix int64) bool {
opendeAt := time.Unix(openedAtUnix, 0)
now := time.Now()
return now.Second()-opendeAt.Second() > 0 // rotate if 1 sec has passed
}))
if err != nil {
panic(err)
}
defer w.Close()
fmt.Fprint(w, "1")
time.Sleep(1 * time.Second)
fmt.Fprint(w, "2") // rotate will start after this writing
time.Sleep(1 * time.Second)
fmt.Fprint(w, "3") // rotate will start after this writing
time.Sleep(1 * time.Second)
fmt.Fprint(w, "4") // rotate will start after this writing
time.Sleep(1 * time.Second) // wait for rotate
b0, _ := ioutil.ReadFile(filepath.Join(dir, "test.log"))
b1, _ := ioutil.ReadFile(filepath.Join(dir, "test.log.1"))
b2, _ := ioutil.ReadFile(filepath.Join(dir, "test.log.2"))
b3, _ := ioutil.ReadFile(filepath.Join(dir, "test.log.3"))
fmt.Printf("%s/%s/%s/%s", b0, b1, b2, b3)
// Output: /4/3/12
}