-
Notifications
You must be signed in to change notification settings - Fork 4
/
file.go
82 lines (66 loc) · 1.33 KB
/
file.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
74
75
76
77
78
79
80
81
82
package jsonlog
import (
"bufio"
"encoding/json"
"fmt"
"log"
"os"
"sync"
)
type M map[string]interface{}
func fexists(name string) bool {
_, err := os.Stat(name)
return err == nil
}
type File struct {
mutex sync.Mutex
f *os.File
w *bufio.Writer
json *json.Encoder
changed bool
}
func NewFile(fileName, fileType string, writeBufferSize int) (*File, error) {
fullName := fileName + ".01" + fileType
for fileID := 2; fexists(fullName); fileID++ {
fullName = fileName + fmt.Sprintf(".%02d", fileID) + fileType
}
f, err := os.OpenFile(fullName, os.O_WRONLY|os.O_CREATE, 0755)
if err != nil {
return nil, err
}
w := bufio.NewWriterSize(f, writeBufferSize)
return &File{
f: f,
w: w,
json: json.NewEncoder(w),
}, nil
}
func (file *File) Write(r M) {
file.mutex.Lock()
defer file.mutex.Unlock()
if err := file.json.Encode(r); err != nil {
log.Println("jsonlog encode failed:", err.Error())
}
file.changed = true
}
func (file *File) Flush() error {
file.mutex.Lock()
defer file.mutex.Unlock()
if !file.changed {
return nil
}
if err := file.w.Flush(); err != nil {
return err
}
if err := file.f.Sync(); err != nil {
return err
}
file.changed = false
return nil
}
func (file *File) Close() error {
if err := file.Flush(); err != nil {
return err
}
return file.f.Close()
}