/
writer.go
97 lines (80 loc) · 1.75 KB
/
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
package log
import (
"context"
"fmt"
"os"
"os/signal"
"sync"
"syscall"
)
var (
RotateSignal = syscall.SIGUSR1
OpenFlag = os.O_CREATE | os.O_APPEND | os.O_WRONLY
OpenPerm = os.FileMode(0644)
)
type Writer struct {
location string
file *os.File
wg sync.WaitGroup
ctx context.Context
cancel context.CancelFunc
}
func NewWriter(location string) (*Writer, error) {
file, err := os.OpenFile(location, OpenFlag, OpenPerm)
if err != nil {
return nil, err
}
ctx, cancel := context.WithCancel(context.Background())
w := &Writer{
location: location,
file: file,
ctx: ctx,
cancel: cancel,
}
w.wg.Add(1)
go w.startRotateListener()
return w, nil
}
func (w *Writer) Write(p []byte) (n int, err error) {
return w.file.Write(p)
}
func (w *Writer) Sync() error {
return w.file.Sync()
}
func (w *Writer) Close() error {
w.cancel()
w.wg.Wait()
return w.file.Close()
}
func (w *Writer) startRotateListener() {
defer func() {
w.wg.Done()
}()
ch := make(chan os.Signal, 1)
signal.Notify(ch, RotateSignal)
for {
select {
case <-w.ctx.Done():
return
case sig := <-ch:
if sig == RotateSignal {
w.rotate()
}
}
}
}
func (w *Writer) rotate() {
file, err := os.OpenFile(w.location, OpenFlag, OpenPerm)
if err != nil {
_, _ = fmt.Fprintf(os.Stderr, "ERROR: failed to rotate log file \"%s\", reopen, reason=%v", w.location, err)
return
}
if err = syscall.Dup2(int(file.Fd()), int(w.file.Fd())); err != nil {
_, _ = fmt.Fprintf(os.Stderr, "ERROR: failed to rotate log file \"%s\", dup2(), reason=%v", w.location, err)
return
}
if err = file.Close(); err != nil {
_, _ = fmt.Fprintf(os.Stderr, "ERROR: failed to close log file \"%s\", close(), reason=%v", w.location, err)
return
}
}