forked from bg5sbk/jsonlog
/
file.go
107 lines (89 loc) · 1.92 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package jsonlog
import (
"bufio"
"compress/gzip"
"encoding/json"
"fmt"
"log"
"os"
"sync"
)
type M map[string]interface{}
type File struct {
mutex sync.Mutex
f *os.File
bufio *bufio.Writer
gzip *gzip.Writer
json *json.Encoder
changed bool
}
func NewFile(fileName, fileType string, compress bool) (*File, error) {
fullName := fileName + fileType
if _, err := os.Stat(fullName); err == nil {
os.Rename(fullName, fileName+".01"+fileType)
fullName = fileName + ".02" + fileType
} else if _, err := os.Stat(fileName + ".01" + fileType); err == nil {
for fileId := 1; true; fileId++ {
fullName = fileName + fmt.Sprintf(".%02d", fileId) + fileType
if _, err := os.Stat(fullName); err != nil {
break
}
}
}
f, err := os.OpenFile(fullName, os.O_WRONLY|os.O_CREATE, 0755)
if err != nil {
return nil, err
}
log := &File{f: f}
if compress {
log.bufio = bufio.NewWriter(log.f)
log.gzip = gzip.NewWriter(log.bufio)
log.json = json.NewEncoder(log.gzip)
} else {
log.bufio = bufio.NewWriter(log.f)
log.json = json.NewEncoder(log.bufio)
}
return log, 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(isClose bool) error {
file.mutex.Lock()
defer file.mutex.Unlock()
if !file.changed {
return nil
}
if file.gzip != nil {
if err := file.gzip.Flush(); err != nil {
return err
}
if isClose {
if err := file.gzip.Close(); err != nil {
return err
}
}
}
if err := file.bufio.Flush(); err != nil {
return err
}
if err := file.f.Sync(); err != nil {
return err
}
file.changed = false
return nil
}
func (file *File) Flush() error {
return file.flush(false)
}
func (file *File) Close() error {
if err := file.flush(true); err != nil {
return err
}
return file.f.Close()
}