-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathfile_writer.go
181 lines (159 loc) · 3.58 KB
/
file_writer.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
package timber
import (
"bytes"
"compress/gzip"
"fmt"
"io"
"math/rand"
"os"
"strings"
"sync"
"text/template"
"time"
)
type FilenameFields struct {
Hostname string
Date time.Time
Pid int
Random int64
}
func GetFilenameFields() *FilenameFields {
h, _ := os.Hostname()
return &FilenameFields{
Hostname: h,
Date: time.Now(),
Pid: os.Getpid(),
Random: rand.Int63(),
}
}
func preprocessFilename(name string) string {
t := template.Must(template.New("filename").Parse(name))
buf := new(bytes.Buffer)
t.Execute(buf, GetFilenameFields())
return buf.String()
}
type FileWriter struct {
wr *BufferedWriter
cwr *countingWriter
BaseFilename string
currentFilename string
mutex *sync.RWMutex
RotateChan chan string // defaults to nil. receives previous filename on rotate
RotateSize int64 // rotate after RotateSize bytes have been written to the file
rotateTicker *time.Ticker
rotateReset chan int
}
// This writer has a buffer that I don't ever bother to flush, so it may take a while
// to see messages. Filenames ending in .gz will automatically be compressed on write.
// Filename string is proccessed through the template library using the FilenameFields
// struct.
func NewFileWriter(name string) (*FileWriter, error) {
w := &FileWriter{
BaseFilename: name,
mutex: new(sync.RWMutex),
}
if err := w.open(); err != nil {
return nil, err
}
return w, nil
}
func (w *FileWriter) open() error {
// No lock here
name := preprocessFilename(w.BaseFilename)
file, err := os.OpenFile(name, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
return fmt.Errorf("TIMBER! Can't open %v: %v", name, err)
}
var cwr = &countingWriter{file, 0}
var output io.WriteCloser = cwr
// Wrap in gz writer
if strings.HasSuffix(name, ".gz") {
output = &gzFileWriter{
gzip.NewWriter(output),
output,
}
}
// Locked from here
w.mutex.Lock()
defer w.mutex.Unlock()
if w.wr != nil {
w.wr.Close()
// send previous filename on rotate chan
if c := w.RotateChan; c != nil {
c <- w.currentFilename
}
}
w.currentFilename = name
w.cwr = cwr
w.wr, _ = NewBufferedWriter(output)
return nil
}
func (w *FileWriter) LogWrite(m string) {
w.mutex.RLock()
defer w.mutex.RUnlock()
w.wr.LogWrite(m)
w.checkSize()
}
func (w *FileWriter) Flush() error {
w.mutex.RLock()
defer w.mutex.RUnlock()
e := w.wr.Flush()
w.checkSize()
return e
}
// Close and re-open the file.
// You should use the timestamp in the filename if you're going to use rotation
func (w *FileWriter) Rotate() error {
return w.open()
}
// Automatically rotate every `d`
func (w *FileWriter) RotateEvery(d time.Duration) {
// reset ticker
w.mutex.Lock()
if w.rotateTicker != nil {
w.rotateTicker.Stop()
w.rotateReset <- 1
}
w.rotateTicker = time.NewTicker(d)
w.mutex.Unlock()
// trigger a rotate every X
go func() {
for {
select {
case <-w.rotateReset:
return
case <-w.rotateTicker.C:
w.Rotate()
}
}
}()
}
func (w *FileWriter) checkSize() {
if w.RotateSize > 0 && w.cwr.bytesWritten >= w.RotateSize {
go w.Rotate()
}
}
func (w *FileWriter) Close() {
w.mutex.Lock()
defer w.mutex.Unlock()
w.wr.Flush()
w.wr.Close()
w.wr = nil
}
type countingWriter struct {
io.WriteCloser
bytesWritten int64
}
func (w *countingWriter) Write(b []byte) (int, error) {
i, e := w.WriteCloser.Write(b)
w.bytesWritten += int64(i)
return i, e
}
type gzFileWriter struct {
*gzip.Writer // the compressor
file io.WriteCloser
}
func (w *gzFileWriter) Close() error {
w.Writer.Close()
return w.file.Close()
}