mirror of
https://github.com/lordmathis/llamactl.git
synced 2025-11-05 16:44:22 +00:00
Fix logger race condition
This commit is contained in:
@@ -7,13 +7,14 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type logger struct {
|
type logger struct {
|
||||||
name string
|
name string
|
||||||
logDir string
|
logDir string
|
||||||
logFile *os.File
|
logFile atomic.Pointer[os.File]
|
||||||
logFilePath string
|
logFilePath string
|
||||||
mu sync.RWMutex
|
mu sync.RWMutex
|
||||||
}
|
}
|
||||||
@@ -47,11 +48,11 @@ func (i *logger) create() error {
|
|||||||
return fmt.Errorf("failed to create stdout log file: %w", err)
|
return fmt.Errorf("failed to create stdout log file: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
i.logFile = logFile
|
i.logFile.Store(logFile)
|
||||||
|
|
||||||
// Write a startup marker to both files
|
// Write a startup marker to both files
|
||||||
timestamp := time.Now().Format("2006-01-02 15:04:05")
|
timestamp := time.Now().Format("2006-01-02 15:04:05")
|
||||||
fmt.Fprintf(i.logFile, "\n=== Instance %s started at %s ===\n", i.name, timestamp)
|
fmt.Fprintf(logFile, "\n=== Instance %s started at %s ===\n", i.name, timestamp)
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -102,11 +103,12 @@ func (i *logger) close() {
|
|||||||
i.mu.Lock()
|
i.mu.Lock()
|
||||||
defer i.mu.Unlock()
|
defer i.mu.Unlock()
|
||||||
|
|
||||||
if i.logFile != nil {
|
logFile := i.logFile.Swap(nil)
|
||||||
|
if logFile != nil {
|
||||||
timestamp := time.Now().Format("2006-01-02 15:04:05")
|
timestamp := time.Now().Format("2006-01-02 15:04:05")
|
||||||
fmt.Fprintf(i.logFile, "=== Instance %s stopped at %s ===\n\n", i.name, timestamp)
|
fmt.Fprintf(logFile, "=== Instance %s stopped at %s ===\n\n", i.name, timestamp)
|
||||||
i.logFile.Close()
|
logFile.Sync() // Ensure all buffered data is written to disk
|
||||||
i.logFile = nil
|
logFile.Close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -117,9 +119,9 @@ func (i *logger) readOutput(reader io.ReadCloser) {
|
|||||||
scanner := bufio.NewScanner(reader)
|
scanner := bufio.NewScanner(reader)
|
||||||
for scanner.Scan() {
|
for scanner.Scan() {
|
||||||
line := scanner.Text()
|
line := scanner.Text()
|
||||||
if i.logFile != nil {
|
// Use atomic load to avoid lock contention on every line
|
||||||
fmt.Fprintln(i.logFile, line)
|
if logFile := i.logFile.Load(); logFile != nil {
|
||||||
i.logFile.Sync() // Ensure data is written to disk
|
fmt.Fprintln(logFile, line)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user