-
Notifications
You must be signed in to change notification settings - Fork 23
/
handler_memory.go
112 lines (91 loc) · 2.33 KB
/
handler_memory.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
package logging
import (
"container/list"
"reflect"
)
func IsNil(i interface{}) bool {
return (i == nil || reflect.ValueOf(i).IsNil())
}
func IsNotNil(i interface{}) bool {
return !IsNil(i)
}
type BufferingHandler interface {
Handler
ShouldFlush(record *LogRecord) bool
}
type BaseBufferingHandler struct {
*BaseHandler
capacity uint64
buffer *list.List
}
func NewBaseBufferingHandler(capacity uint64) *BaseBufferingHandler {
return &BaseBufferingHandler{
BaseHandler: NewBaseHandler("", LevelNotset),
capacity: capacity,
buffer: list.New(),
}
}
func (self *BaseBufferingHandler) GetBuffer() *list.List {
return self.buffer
}
func (self *BaseBufferingHandler) ShouldFlush(_ *LogRecord) bool {
return uint64(self.buffer.Len()) >= self.capacity
}
func (self *BaseBufferingHandler) Emit2(
handler BufferingHandler, record *LogRecord) error {
self.buffer.PushBack(record)
if handler.ShouldFlush(record) {
return handler.Flush()
}
return nil
}
func (self *BaseBufferingHandler) Flush() error {
self.buffer.Init()
return nil
}
func (self *BaseBufferingHandler) Close() {
self.Flush()
}
type MemoryHandler struct {
*BaseBufferingHandler
flushLevel LogLevelType
target Handler
}
func NewMemoryHandler(
capacity uint64, flushLevel LogLevelType, target Handler) *MemoryHandler {
object := &MemoryHandler{
BaseBufferingHandler: NewBaseBufferingHandler(capacity),
flushLevel: flushLevel,
target: target,
}
Closer.AddHandler(object)
return object
}
func (self *MemoryHandler) ShouldFlush(record *LogRecord) bool {
return ((self.BaseBufferingHandler.ShouldFlush(record)) ||
(record.Level >= self.flushLevel))
}
func (self *MemoryHandler) SetTarget(target Handler) {
self.target = target
}
func (self *MemoryHandler) Emit(record *LogRecord) error {
return self.BaseBufferingHandler.Emit2(self, record)
}
func (self *MemoryHandler) Handle(record *LogRecord) int {
return self.Handle2(self, record)
}
func (self *MemoryHandler) Flush() error {
if IsNotNil(self.target) {
buffer := self.BaseBufferingHandler.GetBuffer()
for e := buffer.Front(); e != nil; e = e.Next() {
record, _ := e.Value.(*LogRecord)
self.target.Handle(record)
}
return self.BaseBufferingHandler.Flush()
}
return nil
}
func (self *MemoryHandler) Close() {
self.Flush()
self.BaseBufferingHandler.Close()
}