forked from nytimes/logrotate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logrotate.go
74 lines (62 loc) · 1.49 KB
/
logrotate.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
package logrotate
import (
"fmt"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
// File wraps an *os.File and listens for a 'SIGHUP' signal from logrotated
// so it can reopen the new file.
type File struct {
*os.File
me sync.Mutex
path string
sighup chan os.Signal
}
// NewFile creates a File pointer and kicks off the goroutine listening for
// SIGHUP signals.
func NewFile(path string) (*File, error) {
lr := &File{
me: sync.Mutex{},
path: path,
sighup: make(chan os.Signal, 1),
}
if err := lr.reopen(); err != nil {
return nil, err
}
go func() {
signal.Notify(lr.sighup, syscall.SIGHUP)
for _ = range lr.sighup {
fmt.Fprintf(os.Stderr, "%s: Reopening %q\n", time.Now(), lr.path)
if err := lr.reopen(); err != nil {
fmt.Fprintf(os.Stderr, "%s: Error reopening: %s\n", time.Now(), err)
}
}
}()
return lr, nil
}
func (lr *File) reopen() (err error) {
lr.me.Lock()
defer lr.me.Unlock()
lr.File.Close()
lr.File, err = os.OpenFile(lr.path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
return
}
// Write will write to the underlying file. It uses a sync.Mutex to ensure
// uninterrupted writes during logrotates.
func (lr *File) Write(b []byte) (int, error) {
lr.me.Lock()
defer lr.me.Unlock()
return lr.File.Write(b)
}
// Close will stop the goroutine listening for SIGHUP signals and then close
// the underlying os.File.
func (lr *File) Close() error {
lr.me.Lock()
defer lr.me.Unlock()
signal.Stop(lr.sighup)
close(lr.sighup)
return lr.File.Close()
}