-
Notifications
You must be signed in to change notification settings - Fork 1
/
gologger.go
160 lines (135 loc) · 2.25 KB
/
gologger.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
// @author nikoeleison
package gologger
import (
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"sync"
"time"
)
// @public
// driver struct
// pool section
// writer section
type Driver struct {
pool chan *message
kill chan bool
sm sync.Mutex
swg sync.WaitGroup
path string
prefix string
suffix string
filepath string
file *os.File
writer io.Writer
}
// driver constructor
// dispatch pool
// rotate writer file
func New(path string, prefix string) (d *Driver) {
d = &Driver{}
d.pool = make(chan *message, 100)
d.kill = make(chan bool, 1)
d.dispatch()
d.path = path
d.prefix = prefix
d.rotate(
time.Now().Format(suffixformat),
)
return
}
// kill pool
// consume the rest of message pool
func (d *Driver) Kill() {
d.sm.Lock()
defer d.sm.Unlock()
d.kill <- true
for len(d.pool) > 0 {
msg := <-d.pool
d.consume(msg)
}
d.swg.Wait()
}
// @private
var (
suffixformat = "2006-01-02"
)
// produce new message
// deliver message to consumer
func (d *Driver) produce(level string, s string) {
d.sm.Lock()
defer d.sm.Unlock()
_, file, line, _ := runtime.Caller(2)
d.swg.Add(1)
go func() {
msg := newMsg(
time.Now(),
level,
file,
line,
s,
)
d.pool <- msg
}()
}
// consume message
// rotate writer file
// release message deliver
func (d *Driver) consume(msg *message) {
d.rotate(
msg.now.Format(suffixformat),
)
fmt.Fprint(d.writer, msg.decorate())
d.swg.Done()
}
// rotate writer file
// skip rotate if driver suffix equal to now suffix
// mkdir if not exist
// touch if not exist
func (d *Driver) rotate(suffix string) (err error) {
if d.suffix == suffix {
return nil
}
d.suffix = suffix
d.filepath = fmt.Sprintf(
"%s.log.%s",
d.prefix,
d.suffix,
)
d.filepath = filepath.Join(d.path, d.filepath)
err = os.MkdirAll(
d.path,
os.ModePerm,
)
if err != nil && !os.IsExist(err) {
return
}
d.file, err = os.OpenFile(
d.filepath,
os.O_RDWR|os.O_CREATE|os.O_APPEND,
0666,
)
if err != nil {
return
}
d.writer = io.MultiWriter(os.Stdout, d.file)
return nil
}
// pool dispatcher
// consume message
// break infinite loop
func (d *Driver) dispatch() {
go func() {
for {
select {
case msg := <-d.pool:
d.consume(msg)
case <-d.kill:
break
default:
}
}
}()
}