71 lines
1.5 KiB
Go
71 lines
1.5 KiB
Go
package logger
|
|
|
|
import "sync"
|
|
|
|
// Store 是内存日志环形缓冲,供界面增量拉取。
|
|
type Store struct {
|
|
mu sync.RWMutex
|
|
nextID int64
|
|
max int
|
|
filePath string
|
|
entries []Entry
|
|
}
|
|
|
|
// NewStore 创建内存日志缓冲,最多保留 max 条最新日志。
|
|
func NewStore(max int) *Store {
|
|
if max <= 0 {
|
|
max = 500
|
|
}
|
|
return &Store{
|
|
max: max,
|
|
entries: make([]Entry, 0, max),
|
|
}
|
|
}
|
|
|
|
// Append 追加一条日志,由内部署分配自增 ID;超过容量时丢弃最旧的条目。
|
|
func (s *Store) Append(entry Entry) Entry {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
s.nextID++
|
|
entry.ID = s.nextID
|
|
s.entries = append(s.entries, entry)
|
|
if len(s.entries) > s.max {
|
|
s.entries = append([]Entry(nil), s.entries[len(s.entries)-s.max:]...)
|
|
}
|
|
return entry
|
|
}
|
|
|
|
// Since 返回 ID 大于 since 的日志,用于界面增量拉取。
|
|
func (s *Store) Since(since int64) []Entry {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
out := make([]Entry, 0, len(s.entries))
|
|
for _, entry := range s.entries {
|
|
if entry.ID > since {
|
|
out = append(out, entry)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// Count 返回当前缓冲内的日志条数。
|
|
func (s *Store) Count() int {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
return len(s.entries)
|
|
}
|
|
|
|
// SetFilePath 保存当前日志文件路径。
|
|
func (s *Store) SetFilePath(path string) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
s.filePath = path
|
|
}
|
|
|
|
// FilePath 返回当前日志文件路径。
|
|
func (s *Store) FilePath() string {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
return s.filePath
|
|
}
|