-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocessor.go
116 lines (93 loc) · 1.63 KB
/
processor.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
package log
import (
"fmt"
)
const buffSize = 1024
type processor struct {
mode WriteMode
buf chan *message
}
func NewProcessor(mode WriteMode) *processor {
p := &processor{
mode: mode,
}
if mode == ModeNonBlocking {
p.run()
}
return p
}
func (p *processor) run() {
p.buf = make(chan *message, buffSize)
go func() {
for msg := range p.buf {
if msg != nil {
p.write(msg)
}
}
}()
}
func (p *processor) Do(m *message) {
switch p.mode {
case ModeBlocking:
p.write(m)
case ModeNonBlocking:
p.addToBuf(m)
}
if m.level == Fatal {
panic(m.text)
}
}
func (p *processor) addToBuf(m *message) {
defer func() {
if recover() != nil {
fmt.Println("log: error writing to buffer")
}
}()
select {
case p.buf <- m:
default:
}
}
func (p *processor) write(m *message) {
v, ok := levels[m.level]
if !ok {
return
}
logger := m.super
if v < logger.local.level {
return
}
if len(m.text) == 0 {
return
}
for _, w := range logger.global.writers {
str, err := formatter.Get(&formatterProps{m, w.format})
if err != nil {
continue
}
p.writeByMode(w, str)
}
for _, w := range logger.local.writers {
str, err := formatter.Get(&formatterProps{m, w.format})
if err != nil {
continue
}
p.writeByMode(w, str)
}
}
func (p *processor) writeByMode(w *writer, msg string) {
switch p.mode {
case ModeBlocking:
p.writeSync(w, msg)
case ModeNonBlocking:
p.writeAsync(w, msg)
}
}
func (p *processor) writeAsync(w *writer, msg string) {
fmt.Fprintln(w.writer, msg)
}
func (p *processor) writeSync(w *writer, msg string) {
w.mu.Lock()
fmt.Fprintln(w.writer, msg)
w.mu.Unlock()
}