-
Notifications
You must be signed in to change notification settings - Fork 0
/
writer.go
103 lines (90 loc) · 1.64 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
98
99
100
101
102
103
package logger
import (
"io"
"io/ioutil"
"os"
"sync"
)
var newline = []byte{'\n'}
type Writer interface {
Open() error
Close() error
Reopen() error
WriteLine(s string) error
}
type IOWriter struct {
Writer io.Writer
}
func (o *IOWriter) WriteLine(s string) error {
var err error
_, err = o.Writer.Write(append([]byte(s), newline...))
return err
}
func (o *IOWriter) Open() error {
return nil
}
func (o *IOWriter) Close() error {
return nil
}
func (o *IOWriter) Reopen() error {
return nil
}
var Stdout Writer = &IOWriter{
Writer: os.Stdout,
}
var Stderr Writer = &IOWriter{
Writer: os.Stderr,
}
var Null Writer = &IOWriter{
Writer: ioutil.Discard,
}
type FileWriter struct {
lock sync.RWMutex
Path string
Mode os.FileMode
file *os.File
}
func (o *FileWriter) Open() error {
o.lock.Lock()
defer o.lock.Unlock()
file, err := os.OpenFile(o.Path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, o.Mode)
if err != nil {
return err
}
o.file = file
return nil
}
func (o *FileWriter) Close() error {
o.lock.Lock()
defer o.lock.Unlock()
o.file = nil
return o.file.Close()
}
func (o *FileWriter) WriteLine(s string) error {
o.lock.RLock()
defer o.lock.RUnlock()
var err error
_, err = o.file.Write(append([]byte(s), newline...))
return err
}
func (o *FileWriter) Reopen() error {
var err error
o.lock.Lock()
defer o.lock.Unlock()
err = o.file.Close()
if err != nil {
return err
}
file, err := os.OpenFile(o.Path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, o.Mode)
if err != nil {
return err
}
o.file = file
return nil
}
func NewFileWriter(path string, mode os.FileMode) *FileWriter {
return &FileWriter{
Path: path,
Mode: mode,
}
}