package logger import ( "sync" "douyu_go/internal/types" ) // MemoryLogStore 内存日志缓冲,供前端增量拉取。 type MemoryLogStore struct { mu sync.RWMutex nextID int64 max int filePath string entries []types.LogEntry } // NewMemoryLogStore 创建内存日志缓冲,最多保留 max 条最新日志。 func NewMemoryLogStore(max int) *MemoryLogStore { if max <= 0 { max = 500 } return &MemoryLogStore{ max: max, entries: make([]types.LogEntry, 0, max), } } // Append 追加一条结构化日志,由内部分配自增 ID。 // 超过容量时丢弃最旧的条目,保留最近的 max 条。 func (s *MemoryLogStore) Append(entry types.LogEntry) types.LogEntry { 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 { copy(s.entries, s.entries[len(s.entries)-s.max:]) s.entries = s.entries[:s.max] } return entry } // SetFilePath 保存当前日志文件路径。 func (s *MemoryLogStore) SetFilePath(path string) { s.mu.Lock() defer s.mu.Unlock() s.filePath = path } // Since 返回 ID 大于 since 的日志。 func (s *MemoryLogStore) Since(since int64) []types.LogEntry { s.mu.RLock() defer s.mu.RUnlock() out := make([]types.LogEntry, 0, len(s.entries)) for _, entry := range s.entries { if entry.ID > since { out = append(out, entry) } } return out } // FilePath 返回当前日志文件路径。 func (s *MemoryLogStore) FilePath() string { s.mu.RLock() defer s.mu.RUnlock() return s.filePath }