diff options
| author | SergeiEU <39683682+SergeiEU@users.noreply.github.com> | 2026-04-01 10:17:15 +0400 |
|---|---|---|
| committer | SergeiEU <39683682+SergeiEU@users.noreply.github.com> | 2026-04-01 10:17:15 +0400 |
| commit | 1bd203c5555046b7ee4fbfe2f822eb3d03571ad7 (patch) | |
| tree | d8c85273ede547e03a5727bf185f5d07e87b4a08 /internal/engine/logger.go | |
| download | vpnem-main.tar.gz vpnem-main.tar.bz2 vpnem-main.zip | |
Diffstat (limited to 'internal/engine/logger.go')
| -rw-r--r-- | internal/engine/logger.go | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/internal/engine/logger.go b/internal/engine/logger.go new file mode 100644 index 0000000..c448a56 --- /dev/null +++ b/internal/engine/logger.go @@ -0,0 +1,62 @@ +package engine + +import ( + "os" + "path/filepath" + "sync" +) + +// RingLog keeps last N log lines in memory and optionally writes to file. +type RingLog struct { + mu sync.Mutex + lines []string + max int + file *os.File +} + +// NewRingLog creates a ring buffer logger. +func NewRingLog(maxLines int, dataDir string) *RingLog { + rl := &RingLog{ + lines: make([]string, 0, maxLines), + max: maxLines, + } + if dataDir != "" { + f, err := os.OpenFile(filepath.Join(dataDir, "vpnem.log"), + os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644) + if err == nil { + rl.file = f + } + } + return rl +} + +// Add appends a line. +func (rl *RingLog) Add(line string) { + rl.mu.Lock() + defer rl.mu.Unlock() + + if len(rl.lines) >= rl.max { + rl.lines = rl.lines[1:] + } + rl.lines = append(rl.lines, line) + + if rl.file != nil { + rl.file.WriteString(line + "\n") + } +} + +// Lines returns all current lines. +func (rl *RingLog) Lines() []string { + rl.mu.Lock() + defer rl.mu.Unlock() + cp := make([]string, len(rl.lines)) + copy(cp, rl.lines) + return cp +} + +// Close closes the log file. +func (rl *RingLog) Close() { + if rl.file != nil { + rl.file.Close() + } +} |
