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
|
package logger
import (
"bufio"
"context"
"fmt"
"os"
"os/signal"
"runtime"
"strings"
"sync"
"syscall"
"time"
"github.com/mimecast/dtail/internal/color"
"github.com/mimecast/dtail/internal/config"
)
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"
)
// The configured logging mode(s)
var Mode Modes
// Strategy is the current log strattegy used.
var strategy Strategy
// Synchronise access to logging.
var mutex sync.Mutex
// File descriptor of log file when Mode.logToFile enabled.
var fd *os.File
// File write buffer of log file when Mode.logToFile enabled.
var writer *bufio.Writer
// File write buffer of stdout when Mode.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
// Used to make logging non-blocking.
var fileLogBufCh chan buf
var stdoutBufCh chan string
// Stdout channel, required to pause output
var pauseCh chan struct{}
var resumeCh chan struct{}
// Tell the logger about logrotation
var rotateCh chan os.Signal
// Helper type to make logging non-blocking.
type buf struct {
time time.Time
message string
}
// Start logging.
func Start(ctx context.Context, mode Modes) {
Mode = mode
if Mode.Nothing {
return
}
if Mode.Trace {
Mode.Debug = true
}
strategy := logStrategy()
stdoutWriter = bufio.NewWriter(os.Stdout)
switch strategy {
case DailyStrategy:
_, err := os.Stat(config.Common.LogDir)
Mode.logToFile = !os.IsNotExist(err)
Mode.logToStdout = !Mode.Server || Mode.Debug || Mode.Trace
case StdoutStrategy:
fallthrough
default:
Mode.logToFile = !Mode.Server
Mode.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{})
// Setup logrotation
rotateCh = make(chan os.Signal, 1)
signal.Notify(rotateCh, syscall.SIGHUP)
if Mode.logToStdout {
stdoutBufCh = make(chan string, runtime.NumCPU()*100)
go writeToStdout(ctx)
}
if Mode.logToFile {
fileLogBufCh = make(chan buf, runtime.NumCPU()*100)
go writeToFile(ctx)
}
}
// Info message logging.
func Info(args ...interface{}) string {
if Mode.Server {
return log(serverStr, infoStr, args)
}
return log(clientStr, infoStr, args)
}
// Warn message logging.
func Warn(args ...interface{}) string {
if Mode.Server {
return log(serverStr, warnStr, args)
}
return log(clientStr, warnStr, args)
}
// Error message logging.
func Error(args ...interface{}) string {
if Mode.Server {
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 Mode.Server {
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.Debug {
if Mode.Server {
return log(serverStr, debugStr, args)
}
return log(clientStr, debugStr, args)
}
return ""
}
// Trace message logging.
func Trace(args ...interface{}) string {
if Mode.Trace {
if Mode.Server {
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 Mode.logToStdout {
line := fmt.Sprintf("%s|%s|%s|%s\n", what, hostname, severity, message)
if color.Colored {
line = color.Colorfy(line)
}
stdoutBufCh <- line
}
if Mode.logToFile {
t := time.Now()
timeStr := t.Format("20060102-150405")
fileLogBufCh <- 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.Nothing {
return ""
}
if Mode.Quiet && severity != errorStr && severity != fatalStr {
return ""
}
messages := []string{severity}
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 message
}
// Raw message logging.
func Raw(message string) {
if Mode.Nothing {
return
}
if Mode.logToFile {
fileLogBufCh <- buf{time.Now(), message}
}
if Mode.logToStdout {
if color.Colored {
message = color.Colorfy(message)
}
stdoutBufCh <- 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
}
// Flush all outstanding lines.
func Flush() {
for {
select {
case message := <-stdoutBufCh:
stdoutWriter.WriteString(message)
default:
stdoutWriter.Flush()
return
}
}
}
func writeToStdout(ctx context.Context) {
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 <-ctx.Done():
return
}
}
case <-ctx.Done():
Flush()
return
}
}
}
func writeToFile(ctx context.Context) {
for {
select {
case buf := <-fileLogBufCh:
dateStr := buf.time.Format("20060102")
w := fileWriter(dateStr)
w.WriteString(buf.message)
case <-pauseCh:
PAUSE:
for {
select {
case <-stdoutBufCh:
case <-resumeCh:
break PAUSE
case <-ctx.Done():
return
}
}
case <-ctx.Done():
return
}
}
}
// Pause logging.
func Pause() {
if Mode.logToStdout {
pauseCh <- struct{}{}
}
if Mode.logToFile {
pauseCh <- struct{}{}
}
}
// Resume logging (after pausing).
func Resume() {
if Mode.logToStdout {
resumeCh <- struct{}{}
}
if Mode.logToFile {
resumeCh <- struct{}{}
}
}
|