/
rotate.go
263 lines (217 loc) · 5.49 KB
/
rotate.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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
package rotate
import (
"compress/gzip"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"sync/atomic"
"time"
"ergo.services/ergo/gen"
"ergo.services/ergo/lib"
)
func CreateLogger(options Options) (gen.LoggerBehavior, error) {
var l logger
if options.Path == "" {
dir := filepath.Dir(os.Args[0])
options.Path = filepath.Join(dir, "logs")
}
if strings.HasPrefix(options.Path, "~") {
// home dir
home, _ := os.UserHomeDir()
path := strings.TrimPrefix(options.Path, "~")
options.Path = filepath.Join(home, path)
}
if err := os.MkdirAll(options.Path, 0755); err != nil {
return nil, fmt.Errorf("unable to create %s: %s", options.Path, err)
}
if options.Prefix == "" {
options.Prefix = filepath.Base(os.Args[0])
}
fname := filepath.Join(options.Path, options.Prefix+".log")
file, err := os.OpenFile(fname, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0644)
if err != nil {
return nil, err
}
l.file = file
l.format = "200601021504"
if options.Period < time.Minute {
options.Period = time.Minute
}
l.switchTime = time.Now().Truncate(options.Period).Add(options.Period)
l.suffix = ".log"
if options.Compress {
l.suffix = ".log.gz"
}
l.tformat = options.TimeFormat
if options.ShortLevelName {
l.levelTrace = "[TRC]"
l.levelInfo = "[INF]"
l.levelWarning = "[WRN]"
l.levelError = "[ERR]"
l.levelPanic = "[PNC]"
l.levelDebug = "[DBG]"
} else {
l.levelTrace = fmt.Sprintf("[%s]", gen.LogLevelTrace)
l.levelInfo = fmt.Sprintf("[%s]", gen.LogLevelInfo)
l.levelWarning = fmt.Sprintf("[%s]", gen.LogLevelWarning)
l.levelError = fmt.Sprintf("[%s]", gen.LogLevelError)
l.levelPanic = fmt.Sprintf("[%s]", gen.LogLevelPanic)
l.levelDebug = fmt.Sprintf("[%s]", gen.LogLevelDebug)
}
l.queue = lib.NewQueueMPSC()
l.options = options
return &l, nil
}
type Options struct {
// TimeFormat enables output time in the defined format. See https://pkg.go.dev/time#pkg-constants
// Not defined format makes output time as a timestamp in nanoseconds.
TimeFormat string
// ShortLevelName enables shortnames for the log levels
ShortLevelName bool
// Path directory for the log files
Path string
// Prefix
Prefix string
// Period rotation period
Period time.Duration
// Compress enables gzipping for the log files
Compress bool
// Depth how many log files in the rotation
Depth int
}
type logger struct {
queue lib.QueueMPSC
depth []string
options Options
file *os.File
tformat string // time format
suffix string
switchTime time.Time
format string
levelTrace string
levelInfo string
levelWarning string
levelError string
levelPanic string
levelDebug string
state int32 // 0 - wait, 1 - run, 2 - close
}
func (l *logger) Log(message gen.MessageLog) {
if atomic.LoadInt32(&l.state) == 2 {
// terminated
return
}
l.queue.Push(message)
if atomic.CompareAndSwapInt32(&l.state, 0, 1) == true {
go l.write()
}
}
func (l *logger) Terminate() {
atomic.StoreInt32(&l.state, 2)
l.queue.Push(nil)
if atomic.CompareAndSwapInt32(&l.state, 0, 1) == true {
go l.write()
}
}
func (l *logger) write() {
var level, t, source string
next:
if time.Now().After(l.switchTime) {
l.switchFile()
}
for {
m, ok := l.queue.Pop()
if ok == false {
break
}
message := m.(gen.MessageLog)
if l.tformat == "" {
t = fmt.Sprintf("%d", message.Time.UnixNano())
} else {
t = message.Time.Format(l.tformat)
}
switch message.Level {
case gen.LogLevelInfo:
level = l.levelInfo
case gen.LogLevelWarning:
level = l.levelWarning
case gen.LogLevelError:
level = l.levelError
case gen.LogLevelPanic:
level = l.levelPanic
case gen.LogLevelDebug:
level = l.levelDebug
case gen.LogLevelTrace:
level = l.levelTrace
default:
level = fmt.Sprintf("[%s]", message.Level)
}
switch src := message.Source.(type) {
case gen.MessageLogNode:
source = src.Node.CRC32()
case gen.MessageLogNetwork:
source = fmt.Sprintf("%s-%s", src.Node, src.Peer)
case gen.MessageLogProcess:
source = src.PID.String()
case gen.MessageLogMeta:
source = src.Meta.String()
default:
panic(fmt.Sprintf("unknown log source type: %#v", message.Source))
}
msg := fmt.Sprintf(message.Format, message.Args...)
fmt.Fprintf(l.file, "%s %s %s: %s\n", t, level, source, msg)
}
if atomic.CompareAndSwapInt32(&l.state, 1, 0) == false {
// terminated
l.file.Sync()
l.file.Close()
return
}
if l.queue.Item() == nil {
return
}
// got some in the queue
if atomic.CompareAndSwapInt32(&l.state, 0, 1) == true {
goto next
}
// another goroutine is running
}
func (l *logger) switchFile() {
name := l.options.Prefix + "." + l.switchTime.Add(-l.options.Period).Format(l.format) + l.suffix
// set the next switch time
if l.switchTime.Add(l.options.Period).Before(time.Now()) {
// had no logs longer than the period
l.switchTime = time.Now().Truncate(l.options.Period)
}
l.switchTime = l.switchTime.Add(l.options.Period)
fname := filepath.Join(l.options.Path, name)
out, err := os.Create(fname)
if err != nil {
fmt.Fprintf(os.Stderr, "unable to rotate log file (%s): %s", fname, err)
return
}
// copy current file
l.file.Sync()
l.file.Seek(0, io.SeekStart)
if l.options.Compress {
zout := gzip.NewWriter(out)
io.Copy(zout, l.file)
zout.Close()
} else {
// copy current file
io.Copy(out, l.file)
}
out.Close()
// truncate it
l.file.Truncate(0)
l.file.Seek(0, io.SeekStart)
if l.options.Depth > 0 {
l.depth = append(l.depth, fname)
if len(l.depth) > l.options.Depth {
os.Remove(l.depth[0])
l.depth = l.depth[1:]
}
}
}