|
| 1 | +package models |
| 2 | + |
| 3 | +import ( |
| 4 | + "sync" |
| 5 | + "time" |
| 6 | +) |
| 7 | + |
| 8 | +// LogEntry represents a single log entry for sync operations |
| 9 | +type LogEntry struct { |
| 10 | + Timestamp string `json:"timestamp"` |
| 11 | + Level string `json:"level"` // INFO, WARN, ERROR |
| 12 | + Message string `json:"message"` |
| 13 | + SyncID string `json:"syncId,omitempty"` |
| 14 | + Operation string `json:"operation,omitempty"` |
| 15 | +} |
| 16 | + |
| 17 | +// LogStore manages the in-memory log storage with a max of 100 entries |
| 18 | +type LogStore struct { |
| 19 | + mu sync.RWMutex |
| 20 | + entries []LogEntry |
| 21 | + maxSize int |
| 22 | +} |
| 23 | + |
| 24 | +var ( |
| 25 | + // GlobalLogStore is the global instance of the log store |
| 26 | + GlobalLogStore *LogStore |
| 27 | + once sync.Once |
| 28 | +) |
| 29 | + |
| 30 | +// GetLogStore returns the singleton instance of LogStore |
| 31 | +func GetLogStore() *LogStore { |
| 32 | + once.Do(func() { |
| 33 | + GlobalLogStore = &LogStore{ |
| 34 | + entries: make([]LogEntry, 0, 100), |
| 35 | + maxSize: 100, |
| 36 | + } |
| 37 | + }) |
| 38 | + return GlobalLogStore |
| 39 | +} |
| 40 | + |
| 41 | +// AddLog adds a new log entry to the store |
| 42 | +func (ls *LogStore) AddLog(level, message, syncID, operation string) { |
| 43 | + ls.mu.Lock() |
| 44 | + defer ls.mu.Unlock() |
| 45 | + |
| 46 | + entry := LogEntry{ |
| 47 | + Timestamp: time.Now().Format(time.RFC3339), |
| 48 | + Level: level, |
| 49 | + Message: message, |
| 50 | + SyncID: syncID, |
| 51 | + Operation: operation, |
| 52 | + } |
| 53 | + |
| 54 | + // Add to the end |
| 55 | + ls.entries = append(ls.entries, entry) |
| 56 | + |
| 57 | + // Keep only the last maxSize entries |
| 58 | + if len(ls.entries) > ls.maxSize { |
| 59 | + ls.entries = ls.entries[len(ls.entries)-ls.maxSize:] |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +// GetLogs returns the last N log entries (or all if N > total) |
| 64 | +func (ls *LogStore) GetLogs(last int) []LogEntry { |
| 65 | + ls.mu.RLock() |
| 66 | + defer ls.mu.RUnlock() |
| 67 | + |
| 68 | + if last <= 0 || last > len(ls.entries) { |
| 69 | + // Return all entries in reverse order (newest first) |
| 70 | + result := make([]LogEntry, len(ls.entries)) |
| 71 | + for i, entry := range ls.entries { |
| 72 | + result[len(ls.entries)-1-i] = entry |
| 73 | + } |
| 74 | + return result |
| 75 | + } |
| 76 | + |
| 77 | + // Return last N entries in reverse order (newest first) |
| 78 | + result := make([]LogEntry, last) |
| 79 | + for i := 0; i < last; i++ { |
| 80 | + result[i] = ls.entries[len(ls.entries)-1-i] |
| 81 | + } |
| 82 | + return result |
| 83 | +} |
0 commit comments