-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathlogbuffer.go
More file actions
62 lines (57 loc) · 1.51 KB
/
Copy pathlogbuffer.go
File metadata and controls
62 lines (57 loc) · 1.51 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
package agentfleet
import (
"bytes"
"sync"
)
// LogBuffer is a thread-safe line-oriented ring buffer that implements io.Writer.
// Pass it to slog.NewTextHandler to capture log output; read Lines() in the TUI.
type LogBuffer struct {
mu sync.RWMutex
lines []string
max int
acc []byte
}
// NewLogBuffer returns a LogBuffer keeping at most maxLines lines.
func NewLogBuffer(maxLines int) *LogBuffer {
if maxLines <= 0 {
maxLines = 200
}
return &LogBuffer{max: maxLines}
}
// Write implements io.Writer. Lines are split on '\n'; incomplete lines are
// buffered until the next Write that completes them.
func (b *LogBuffer) Write(p []byte) (int, error) {
const maxAccBytes = 64 * 1024
b.mu.Lock()
defer b.mu.Unlock()
b.acc = append(b.acc, p...)
// Cap unbounded growth if acc exceeds max without encountering newlines
if len(b.acc) > maxAccBytes {
b.acc = b.acc[len(b.acc)-maxAccBytes:]
}
for {
idx := bytes.IndexByte(b.acc, '\n')
if idx < 0 {
break
}
line := string(b.acc[:idx])
b.acc = b.acc[idx+1:]
if len(b.lines) >= b.max {
b.lines = b.lines[1:]
}
b.lines = append(b.lines, line)
}
// Compact acc backing array if it has grown too large relative to its content
if cap(b.acc) > len(b.acc)*4 && len(b.acc) > 0 {
b.acc = append([]byte(nil), b.acc...)
}
return len(p), nil
}
// Lines returns a snapshot of buffered lines, oldest first.
func (b *LogBuffer) Lines() []string {
b.mu.RLock()
defer b.mu.RUnlock()
out := make([]string, len(b.lines))
copy(out, b.lines)
return out
}