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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
|
package logger
import (
"bufio"
"dtail/color"
"dtail/config"
"fmt"
"os"
"os/signal"
"runtime"
"strings"
"sync"
"syscall"
"time"
)
const (
clientStr string = "CLIENT"
serverStr string = "SERVER"
infoStr string = "INFO"
warnStr string = "WARN"
errorStr string = "ERROR"
fatalStr string = "FATAL"
debugStr string = "DEBUG"
traceStr string = "TRACE"
)
// Synchronise access to logging.
var mutex sync.Mutex
// File descriptor of log file when logToFile enabled.
var fd *os.File
// File write buffer of log file when logToFile enabled.
var writer *bufio.Writer
// File write buffer of stdout when logToStdout enabled.
var stdoutWriter *bufio.Writer
// Current hostname.
var hostname string
// Used to detect change of day (create one log file per day0
var lastDateStr string
// True if log in server mode, false if log in client mode.
var serverEnable bool
// Used to make logging non-blocking.
var logBufCh chan buf
var stdoutBufCh chan string
// Stdout channel, required to pause output
var pauseCh chan struct{}
var resumeCh chan struct{}
// Tell the logger that we are done, program shuts down
var stop chan struct{}
var stdoutFlushed chan struct{}
// Tell the logger about logrotation
var rotateCh chan os.Signal
// LogMode allows to specify the verbosity of logging.
type LogMode int
// Possible log modes.
const (
NormalMode LogMode = iota
DebugMode LogMode = iota
SilentMode LogMode = iota
TraceMode LogMode = iota
NothingMode LogMode = iota
)
// Mode is the current log mode in use.
var Mode LogMode
// LogStrategy allows to specify a log rotation strategy.
type LogStrategy int
// Possible log strategies.
const (
NormalStrategy LogStrategy = iota
DailyStrategy LogStrategy = iota
StdoutStrategy LogStrategy = iota
)
// Strategy is the current log strattegy used.
var Strategy LogStrategy
// Enables logging to stdout.
var logToStdout bool
// Enables logging to file.
var logToFile bool
// Helper type to make logging non-blocking.
type buf struct {
time time.Time
message string
}
// Init logging.
func Init(myServerEnable bool, mode LogMode, strategy LogStrategy) {
stdoutWriter = bufio.NewWriter(os.Stdout)
serverEnable = myServerEnable
Mode = mode
Strategy = strategy
if Mode == NothingMode {
return
}
switch Strategy {
case DailyStrategy:
_, err := os.Stat(config.Common.LogDir)
logToFile = !os.IsNotExist(err)
logToStdout = !serverEnable || Mode == DebugMode || Mode == TraceMode
case StdoutStrategy:
fallthrough
default:
logToFile = false
logToStdout = true
}
fqdn, err := os.Hostname()
if err != nil {
panic(err)
}
s := strings.Split(fqdn, ".")
hostname = s[0]
pauseCh = make(chan struct{})
resumeCh = make(chan struct{})
stop = make(chan struct{})
stdoutFlushed = make(chan struct{})
// Setup logrotation
rotateCh = make(chan os.Signal, 1)
signal.Notify(rotateCh, syscall.SIGHUP)
if logToStdout {
stdoutBufCh = make(chan string, runtime.NumCPU()*100)
go writeToStdout()
}
if logToFile {
logBufCh = make(chan buf, runtime.NumCPU()*100)
go writeToFile()
}
}
// Info message logging.
func Info(args ...interface{}) string {
if serverEnable {
return log(serverStr, infoStr, args)
}
return log(clientStr, infoStr, args)
}
// Warn message logging.
func Warn(args ...interface{}) string {
if serverEnable {
return log(serverStr, warnStr, args)
}
return log(clientStr, warnStr, args)
}
// Error message logging.
func Error(args ...interface{}) string {
if serverEnable {
return log(serverStr, errorStr, args)
}
return log(clientStr, errorStr, args)
}
// FatalExit logs an error and exists the process.
func FatalExit(args ...interface{}) {
what := clientStr
if serverEnable {
what = serverStr
}
log(what, fatalStr, args)
time.Sleep(time.Second)
mutex.Lock()
defer mutex.Unlock()
closeWriter()
os.Exit(3)
}
// Debug message logging.
func Debug(args ...interface{}) string {
if Mode == DebugMode || Mode == TraceMode {
if serverEnable {
return log(serverStr, debugStr, args)
}
return log(clientStr, debugStr, args)
}
return ""
}
// Trace message logging.
func Trace(args ...interface{}) string {
if Mode == TraceMode {
if serverEnable {
return log(serverStr, traceStr, args)
}
return log(clientStr, traceStr, args)
}
return ""
}
// Write log line to buffer and/or log file.
func write(what, severity, message string) {
if logToStdout && (Mode != SilentMode || severity != warnStr) {
line := fmt.Sprintf("%s|%s|%s|%s\n", what, hostname, severity, message)
if color.Colored {
line = color.Colorfy(line)
}
stdoutBufCh <- line
}
if logToFile {
t := time.Now()
timeStr := t.Format("20060102-150405")
logBufCh <- buf{
time: t,
message: fmt.Sprintf("%s|%s|%s|%s\n", severity, timeStr, what, message),
}
}
}
// Generig log message.
func log(what string, severity string, args []interface{}) string {
if Mode == NothingMode {
return ""
}
var messages []string
for _, arg := range args {
switch v := arg.(type) {
case string:
messages = append(messages, v)
case int:
messages = append(messages, fmt.Sprintf("%d", v))
case error:
messages = append(messages, v.Error())
default:
messages = append(messages, fmt.Sprintf("%v", v))
}
}
message := strings.Join(messages, "|")
write(what, severity, message)
return fmt.Sprintf("%s|%s", severity, message)
}
// Raw message logging.
func Raw(message string) {
if Mode == NothingMode {
return
}
if logToStdout {
if color.Colored {
message = color.Colorfy(message)
}
stdoutBufCh <- message
}
if logToFile {
logBufCh <- buf{time.Now(), message}
}
}
// Close log writer (e.g. on change of day).
func closeWriter() {
if writer != nil {
writer.Flush()
fd.Close()
}
}
// Return the correct log file writer
func fileWriter(dateStr string) *bufio.Writer {
if dateStr != lastDateStr {
return updateFileWriter(dateStr)
}
// Check for log rotation signal
select {
case <-rotateCh:
stdoutWriter.WriteString("Received signal for logrotation\n")
return updateFileWriter(dateStr)
default:
}
return writer
}
// Update log file writer
func updateFileWriter(dateStr string) *bufio.Writer {
// Detected change of day. Close current writer and create a new one.
mutex.Lock()
defer mutex.Unlock()
closeWriter()
if _, err := os.Stat(config.Common.LogDir); os.IsNotExist(err) {
if err = os.MkdirAll(config.Common.LogDir, 0755); err != nil {
panic(err)
}
}
logFile := fmt.Sprintf("%s/%s.log", config.Common.LogDir, dateStr)
newFd, err := os.OpenFile(logFile, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)
if err != nil {
panic(err)
}
fd = newFd
writer = bufio.NewWriterSize(fd, 1)
lastDateStr = dateStr
return writer
}
func flushStdout() {
defer close(stdoutFlushed)
for {
select {
case message := <-stdoutBufCh:
stdoutWriter.WriteString(message)
default:
stdoutWriter.Flush()
return
}
}
}
func writeToStdout() {
for {
select {
case message := <-stdoutBufCh:
stdoutWriter.WriteString(message)
case <-time.After(time.Millisecond * 100):
stdoutWriter.Flush()
case <-pauseCh:
PAUSE:
for {
select {
case <-stdoutBufCh:
case <-resumeCh:
break PAUSE
case <-stop:
return
}
}
case <-stop:
flushStdout()
return
}
}
}
func writeToFile() {
for {
select {
case buf := <-logBufCh:
dateStr := buf.time.Format("20060102")
w := fileWriter(dateStr)
w.WriteString(buf.message)
case <-pauseCh:
PAUSE:
for {
select {
case <-stdoutBufCh:
case <-resumeCh:
break PAUSE
case <-stop:
return
}
}
case <-stop:
return
}
}
}
// Pause logging.
func Pause() {
if logToStdout {
pauseCh <- struct{}{}
}
if logToFile {
pauseCh <- struct{}{}
}
}
// Resume logging (after pausing).
func Resume() {
if logToStdout {
resumeCh <- struct{}{}
}
if logToFile {
resumeCh <- struct{}{}
}
}
// Stop logging.
func Stop() {
close(stop)
<-stdoutFlushed
}
|