-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
117 lines (98 loc) · 2.03 KB
/
logger.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
117
package logger
import (
"sort"
"sync"
"time"
"github.com/Tympanix/artoodetoo/types"
)
// History is a slice of entries
type History []*Entry
func (l History) Len() int {
return len(l)
}
func (l History) Less(i, j int) bool {
return l[i].Time < l[j].Time
}
func (l History) Swap(i, j int) {
l[i], l[j] = l[j], l[i]
}
var logs History
var lock = new(sync.RWMutex)
// Entry is a log entry in the log
type Entry struct {
Type string `json:"type"`
Task string `json:"task"`
Event string `json:"event"`
Message string `json:"message"`
Time int64 `json:"time"`
}
func (e *Entry) Error() string {
return e.Message
}
// SetTask binds a task to the given error
func (e *Entry) SetTask(t types.Identifiable) *Entry {
e.Task = t.ID()
return e
}
// SetEvent bind an event to the given error
func (e *Entry) SetEvent(t types.Identifiable) *Entry {
e.Event = t.ID()
return e
}
// Log appends the entry to the log history
func (e *Entry) Log() {
Log(e)
}
// Convert converts an error intro a log entry
func Convert(err error) *Entry {
return getOrCreate(err)
}
// NewError returns a new entry for logging
func NewError(err string) *Entry {
return &Entry{
Type: "error",
Message: err,
Time: time.Now().Unix(),
}
}
// NewSuccess returns a new successful log entry
func NewSuccess(err string) *Entry {
return &Entry{
Type: "success",
Message: err,
Time: time.Now().Unix(),
}
}
func getOrCreate(err error) *Entry {
if e, ok := err.(*Entry); ok {
return e
}
return NewError(err.Error())
}
// Log logs a new error to the history
func Log(err error) {
lock.RLock()
defer lock.RUnlock()
logs = append(logs, getOrCreate(err))
}
// Get retrieved log newer than a specified time
func Get(time int64) History {
lock.RLock()
defer lock.RUnlock()
log := make(History, 0)
for i := len(logs) - 1; i >= 0; i-- {
if logs[i].Time > time {
log = append(log, logs[i])
} else {
break
}
}
sort.Sort(log)
return log
}
// Clear clears the log
func Clear() {
lock.Lock()
lock.Unlock()
logs = make(History, 0)
}