-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlog_cache.go
More file actions
47 lines (38 loc) · 802 Bytes
/
log_cache.go
File metadata and controls
47 lines (38 loc) · 802 Bytes
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
package main
import (
"sync"
)
type LogCache struct {
mu sync.Mutex
logs []string
size int
}
func newLogCache(size int) *LogCache {
return &LogCache{
size: size,
logs: make([]string, 0, size),
}
}
func (lc *LogCache) Write(p []byte) (n int, err error) {
lc.mu.Lock()
defer lc.mu.Unlock()
msg := string(p)
// Remove trailing newline if present for cleaner display
if len(msg) > 0 && msg[len(msg)-1] == '\n' {
msg = msg[:len(msg)-1]
}
lc.logs = append(lc.logs, msg)
if len(lc.logs) > lc.size {
// Keep the last `size` elements
lc.logs = lc.logs[len(lc.logs)-lc.size:]
}
return len(p), nil
}
func (lc *LogCache) GetLogs() []string {
lc.mu.Lock()
defer lc.mu.Unlock()
// Return a copy
result := make([]string, len(lc.logs))
copy(result, lc.logs)
return result
}