-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
events.go
112 lines (92 loc) · 1.83 KB
/
events.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 session
import (
"fmt"
"os"
"sort"
"sync"
"time"
"github.com/bettercap/bettercap/core"
)
type Event struct {
Tag string `json:"tag"`
Time time.Time `json:"time"`
Data interface{} `json:"data"`
}
type LogMessage struct {
Level int
Message string
}
func NewEvent(tag string, data interface{}) Event {
return Event{
Tag: tag,
Time: time.Now(),
Data: data,
}
}
func (e Event) Label() string {
log := e.Data.(LogMessage)
label := core.LogLabels[log.Level]
color := core.LogColors[log.Level]
return color + label + core.RESET
}
type EventPool struct {
sync.Mutex
NewEvents chan Event
debug bool
silent bool
events []Event
}
func NewEventPool(debug bool, silent bool) *EventPool {
return &EventPool{
NewEvents: make(chan Event, 0xff),
debug: debug,
silent: silent,
events: make([]Event, 0),
}
}
func (p *EventPool) SetSilent(s bool) {
p.Lock()
defer p.Unlock()
p.silent = s
}
func (p *EventPool) SetDebug(d bool) {
p.Lock()
defer p.Unlock()
p.debug = d
}
func (p *EventPool) Add(tag string, data interface{}) {
p.Lock()
defer p.Unlock()
e := NewEvent(tag, data)
p.events = append([]Event{e}, p.events...)
p.NewEvents <- e
}
func (p *EventPool) Log(level int, format string, args ...interface{}) {
if level == core.DEBUG && p.debug == false {
return
} else if level < core.ERROR && p.silent == true {
return
}
message := fmt.Sprintf(format, args...)
p.Add("sys.log", LogMessage{
level,
message,
})
if level == core.FATAL {
fmt.Fprintf(os.Stderr, "%s\n", message)
os.Exit(1)
}
}
func (p *EventPool) Clear() {
p.Lock()
defer p.Unlock()
p.events = make([]Event, 0)
}
func (p *EventPool) Sorted() []Event {
p.Lock()
defer p.Unlock()
sort.Slice(p.events, func(i, j int) bool {
return p.events[i].Time.Before(p.events[j].Time)
})
return p.events
}