forked from AlexStocks/log4go
/
termlog.go
executable file
·111 lines (98 loc) · 2.46 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
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
// Copyright (C) 2010, Kyle Lemons <kyle@kylelemons.net>. All rights reserved.
package log4go
import (
"fmt"
"io"
"os"
"reflect"
"sync"
"time"
"unsafe"
)
var stdout io.Writer = os.Stdout
// This is the standard writer that prints to standard output.
type ConsoleLogWriter struct {
json bool
format string
lock sync.Mutex
w chan *LogRecord
sync.Once
}
// This creates a new ConsoleLogWriter
func NewConsoleLogWriter(json bool) *ConsoleLogWriter {
consoleWriter := &ConsoleLogWriter{
json: json,
format: "[%T %D] [%L] (%S) %M",
w: make(chan *LogRecord, LogBufferLength),
}
go consoleWriter.run(stdout)
return consoleWriter
}
func (c *ConsoleLogWriter) SetJson(json bool) {
c.json = json
}
func (c *ConsoleLogWriter) SetFormat(format string) {
c.format = format
}
func String(b []byte) (s string) {
pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b))
pstring := (*reflect.StringHeader)(unsafe.Pointer(&s))
pstring.Data = pbytes.Data
pstring.Len = pbytes.Len
return
}
func Slice(s string) (b []byte) {
pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b))
pstring := (*reflect.StringHeader)(unsafe.Pointer(&s))
pbytes.Data = pstring.Data
pbytes.Len = pstring.Len
pbytes.Cap = pstring.Len
return
}
func (c *ConsoleLogWriter) run(out io.Writer) {
//for rec := range c.w {
// fmt.Fprint(out, FormatLogRecord(c.format, rec))
//}
var logString string
for rec := range c.w {
if !c.json {
logString = FormatLogRecord(c.format, rec)
} else {
recBytes := append(rec.JSON(), Slice(newLine)...)
logString = String(recBytes)
}
switch rec.Level {
case FINEST, FINE, DEBUG:
cDebug(out, logString)
case TRACE:
cTrace(out, logString)
case INFO:
cInfo(out, logString)
case WARNING:
cWarn(out, logString)
case ERROR:
cError(out, logString)
case CRITICAL:
cCritical(out, logString)
}
}
}
// This is the ConsoleLogWriter's output method. This will block if the output
// buffer is full.
func (c *ConsoleLogWriter) LogWrite(rec *LogRecord) {
defer func() {
if e := recover(); e != nil {
fmt.Printf(FormatLogRecord("term log channel has been closed."+c.format, rec))
}
}()
c.w <- 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 (c *ConsoleLogWriter) Close() {
c.Once.Do(func() {
close(c.w)
c.w = nil
time.Sleep(50 * time.Millisecond) // Try to give console I/O time to complete
})
}