-
Notifications
You must be signed in to change notification settings - Fork 0
/
logfile.go
62 lines (55 loc) · 963 Bytes
/
logfile.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
// +build !windows
package fs
import (
"log"
"os"
"os/signal"
"path/filepath"
"sync"
"syscall"
)
type LogFile struct {
path string
sync.RWMutex
*os.File
}
func NewLogFile(path string) (*LogFile, error) {
l := LogFile{path: path}
if err := l.open(); err != nil {
return nil, err
}
ch := make(chan os.Signal)
signal.Notify(ch, syscall.SIGUSR1)
go func() {
for {
<-ch
if err := l.open(); err != nil {
log.Println(err)
}
}
}()
return &l, nil
}
func (l *LogFile) open() error {
if err := os.MkdirAll(filepath.Dir(l.path), 0775); err != nil {
return err
}
file, err := os.OpenFile(l.path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
return err
}
l.Lock()
defer l.Unlock()
if l.File != nil {
if err := l.File.Close(); err != nil {
log.Println(err)
}
}
l.File = file
return nil
}
func (l *LogFile) Write(b []byte) (n int, err error) {
l.RLock()
defer l.RUnlock()
return l.File.Write(b)
}