-
Notifications
You must be signed in to change notification settings - Fork 66
/
ring.go
73 lines (57 loc) · 1.26 KB
/
ring.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
package minilog
import (
"container/ring"
"fmt"
"strconv"
"sync"
"time"
)
type Ring struct {
size int
// guards below
mu sync.Mutex
r *ring.Ring
}
func NewRing(size int) *Ring {
return &Ring{
r: ring.New(size),
size: size,
}
}
// Println mimic golang's log.Logger.Output and prepends the time
func (l *Ring) Println(v ...interface{}) {
now := time.Now()
l.mu.Lock()
defer l.mu.Unlock()
var buf []byte
year, month, day := now.Date()
buf = strconv.AppendInt(buf, int64(year), 10)
buf = append(buf, '/')
buf = strconv.AppendInt(buf, int64(month), 10)
buf = append(buf, '/')
buf = strconv.AppendInt(buf, int64(day), 10)
buf = append(buf, ' ')
hour, min, sec := now.Clock()
buf = strconv.AppendInt(buf, int64(hour), 10)
buf = append(buf, ':')
buf = strconv.AppendInt(buf, int64(min), 10)
buf = append(buf, ':')
buf = strconv.AppendInt(buf, int64(sec), 10)
buf = append(buf, ' ')
buf = append(buf, fmt.Sprintln(v...)...)
l.r = l.r.Next()
l.r.Value = string(buf)
}
// Dump returns the log messages from oldest to newest.
func (l *Ring) Dump() []string {
l.mu.Lock()
defer l.mu.Unlock()
res := make([]string, 0, l.size)
l.r.Next().Do(func(v interface{}) {
if v == nil {
return
}
res = append(res, v.(string))
})
return res
}