-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlog_buffer.go
More file actions
65 lines (53 loc) · 1.25 KB
/
log_buffer.go
File metadata and controls
65 lines (53 loc) · 1.25 KB
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
package main
import (
"strings"
"sync"
)
// LogBuffer stores recent log lines in memory.
type LogBuffer struct {
mu sync.RWMutex
entries []string
maxEntries int
partial string
}
func NewLogBuffer(maxEntries int) *LogBuffer {
if maxEntries <= 0 {
maxEntries = 100
}
return &LogBuffer{
entries: make([]string, 0, maxEntries),
maxEntries: maxEntries,
}
}
// Write implements io.Writer so this can be used as a log output sink.
func (lb *LogBuffer) Write(p []byte) (n int, err error) {
lb.mu.Lock()
defer lb.mu.Unlock()
chunk := lb.partial + string(p)
lines := strings.Split(chunk, "\n")
// If chunk doesn't end with newline, keep the tail for next write.
if !strings.HasSuffix(chunk, "\n") {
lb.partial = lines[len(lines)-1]
lines = lines[:len(lines)-1]
} else {
lb.partial = ""
}
for _, line := range lines {
line = strings.TrimSuffix(line, "\r")
if line == "" {
continue
}
lb.entries = append(lb.entries, line)
}
if len(lb.entries) > lb.maxEntries {
lb.entries = lb.entries[len(lb.entries)-lb.maxEntries:]
}
return len(p), nil
}
func (lb *LogBuffer) GetEntries() []string {
lb.mu.RLock()
defer lb.mu.RUnlock()
entries := make([]string, len(lb.entries))
copy(entries, lb.entries)
return entries
}