-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtermlog.go
55 lines (45 loc) · 1.32 KB
/
termlog.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
// Copyright (C) 2010, Kyle Lemons <kyle@kylelemons.net>. All rights reserved.
package log4go
import (
"fmt"
"io"
"os"
)
// ConsoleLogWriter is the standard writer that prints to standard output.
//type ConsoleLogWriter chan *LogRecord
type ConsoleLogWriter struct {
logChan chan *LogRecord
wg waitGroupWrapper
stdout io.Writer
}
// NewConsoleLogWriter creates a new ConsoleLogWriter
func NewConsoleLogWriter() *ConsoleLogWriter {
w := &ConsoleLogWriter{
logChan: make(chan *LogRecord, LogBufferLength),
stdout: os.Stdout,
}
w.wg.Wrap(func() { w.run() })
return w
}
func (w *ConsoleLogWriter) run() {
var timestr string
var timestrAt int64
out := w.stdout
for rec := range w.logChan {
if at := rec.Created.UnixNano() / 1e9; at != timestrAt {
timestr, timestrAt = rec.Created.Format("01/02/06 15:04:05"), at
}
fmt.Fprint(out, "[", timestr, "] [", levelStrings[rec.Level], "] ", rec.Message, "\n")
}
}
// LogWrite is the ConsoleLogWriter's output method. This will block if the output
// buffer is full.
func (w *ConsoleLogWriter) LogWrite(rec *LogRecord) {
w.logChan <- rec
}
// Close stops the logger from sending messages to standard output. Attempts to
// send log messages to this logger after a Close have undefined behavior.
func (w *ConsoleLogWriter) Close() {
close(w.logChan)
w.wg.Wait()
}