-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmock_log.go
69 lines (60 loc) · 1.08 KB
/
mock_log.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
package logpeck
import (
"fmt"
"math/rand"
"os"
"sync"
"time"
)
// MockLog .
type MockLog struct {
Path string
IsRunning bool
stop bool
file *os.File
mu sync.Mutex
}
// NewMockLog .
func NewMockLog(path string) (*MockLog, error) {
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
return nil, err
}
return &MockLog{Path: path, IsRunning: false, file: f, stop: false}, nil
}
func genLog() string {
now := time.Now().String()
randNum := rand.Intn(65536)
return fmt.Sprintf("%s mocklog %d .\n", now, randNum)
}
// Run .
func (p *MockLog) Run() error {
p.mu.Lock()
defer p.mu.Unlock()
if p.IsRunning {
return fmt.Errorf("log[%s] already running", p.Path)
}
p.IsRunning = true
for !p.stop {
p.file.WriteString(genLog())
p.mu.Unlock()
time.Sleep(1027 * time.Millisecond)
p.mu.Lock()
}
p.IsRunning = false
p.stop = false
return nil
}
// Stop .
func (p *MockLog) Stop() {
p.mu.Lock()
defer p.mu.Unlock()
p.stop = true
}
// Close .
func (p *MockLog) Close() {
p.Stop()
p.mu.Lock()
defer p.mu.Unlock()
p.file.Close()
}