-
Notifications
You must be signed in to change notification settings - Fork 0
/
writer_file_mixed.go
121 lines (114 loc) · 2.53 KB
/
writer_file_mixed.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package tlog
import (
"errors"
"fmt"
"os"
"path"
"sync"
"syscall"
)
type WriteToFileMixed struct {
newFileYear int
newFileMonth int
newFileDay int
fd int
dir string
logFilePrefix string
fileStoreMode FileStoreModeT
mtx sync.Mutex
}
func NewWriteToFileMixed(opts ...Option) Writer {
opt := setOptions(opts...)
w := &WriteToFileMixed{
fd: -1,
dir: opt.logDir,
logFilePrefix: opt.logFilePrefix,
fileStoreMode: opt.fileStoreMode,
}
if w.dir != "" {
if err := os.MkdirAll(w.dir, 0755); err != nil {
panic(errors.New("newlog mkdir fail! " + err.Error()))
}
}
if w.fileStoreMode == AppendOneFile {
if err := w.openAppendFile(); err != nil {
panic(errors.New("newlog open file fail! " + err.Error()))
}
}
return w
}
func (w *WriteToFileMixed) Write(e Encoder, p []byte) (n int, err error) {
now := e.Now()
year, month, day := now.Date()
w.mtx.Lock()
defer w.mtx.Unlock()
if w.fileStoreMode == DailySplit {
if err = w.newFile(year, int(month), day); err != nil {
return
}
}
for {
n, err = syscall.Write(w.fd, p)
if err != nil && err == syscall.EINTR {
continue
}
break
}
return
}
func (w *WriteToFileMixed) newFile(year, month, day int) error {
if w.newFileYear != year || w.newFileMonth != month || w.newFileDay != day {
w.close()
if err := w.openSeparateFile(year, month, day); err != nil {
return err
}
}
return nil
}
func (w *WriteToFileMixed) openAppendFile() (err error) {
var fname string
if len(w.logFilePrefix) == 0 {
fname = fmt.Sprintf("%s.log", "tlog")
} else {
fname = fmt.Sprintf("%s.log", w.logFilePrefix)
}
logFile := path.Join(w.dir, fname)
for {
w.fd, err = syscall.Open(logFile, syscall.O_CREAT|syscall.O_WRONLY|syscall.O_APPEND, 0644)
if err != nil {
if err == syscall.EINTR {
continue
}
return err
}
break
}
return nil
}
func (w *WriteToFileMixed) openSeparateFile(year, month, day int) (err error) {
var fname string
if len(w.logFilePrefix) == 0 {
fname = fmt.Sprintf("%d-%02d-%02d.log", year, month, day)
} else {
fname = fmt.Sprintf("%s-%d-%02d-%02d.log", w.logFilePrefix, year, month, day)
}
logFile := path.Join(w.dir, fname)
for {
w.fd, err = syscall.Open(logFile, syscall.O_CREAT|syscall.O_WRONLY|syscall.O_APPEND, 0644)
if err != nil {
if err == syscall.EINTR {
continue
}
return err
}
break
}
w.newFileYear, w.newFileMonth, w.newFileDay = year, month, day
return nil
}
func (w *WriteToFileMixed) close() {
if w.fd != -1 {
syscall.Close(w.fd)
w.fd = -1
}
}