Skip to content

Commit 66e8056

Browse files
committed
llm, utils: add logfile rotation logic
1 parent 2ed4b2d commit 66e8056

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

Diff for: llm/llm.go

+6
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
)
1212

1313
const LLMRawLogFile = ".message_log.txt"
14+
const LLMRawLogFileRotationCount = 5
1415

1516
type QueryStatus int
1617

@@ -189,3 +190,8 @@ func GetSimpleRawMessageLogger(perpetualDir string) func(v ...any) {
189190
}
190191
return logFunc
191192
}
193+
194+
func RotateLLMRawLogFile(perpetualDir string) error {
195+
logFilePath := filepath.Join(perpetualDir, LLMRawLogFile)
196+
return utils.RotateFiles(logFilePath, LLMRawLogFileRotationCount)
197+
}

Diff for: utils/file_helpers.go

+33
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,39 @@ func AppendToTextFile(filePath string, text string) error {
169169
return nil
170170
}
171171

172+
func RotateFiles(baseFilePath string, count int) error {
173+
// Check if the base file exists
174+
if _, err := os.Stat(baseFilePath); os.IsNotExist(err) {
175+
// Base file doesn't exist, nothing to rotate
176+
return nil
177+
}
178+
179+
// Remove the oldest rotation file if it exists
180+
oldestFile := fmt.Sprintf("%s.%d", baseFilePath, count-1)
181+
_ = os.Remove(oldestFile) // Ignore error if file doesn't exist
182+
183+
// Shift all existing rotation files by one position
184+
for i := count - 2; i >= 0; i-- {
185+
oldFile := fmt.Sprintf("%s.%d", baseFilePath, i)
186+
newFile := fmt.Sprintf("%s.%d", baseFilePath, i+1)
187+
188+
// Check if the old file exists before attempting to rename
189+
if _, err := os.Stat(oldFile); err == nil {
190+
if err := os.Rename(oldFile, newFile); err != nil {
191+
return fmt.Errorf("failed to rename %s to %s: %w", oldFile, newFile, err)
192+
}
193+
}
194+
}
195+
196+
// Rename the base file to .0
197+
newFile := fmt.Sprintf("%s.0", baseFilePath)
198+
if err := os.Rename(baseFilePath, newFile); err != nil {
199+
return fmt.Errorf("failed to rename %s to %s: %w", baseFilePath, newFile, err)
200+
}
201+
202+
return nil
203+
}
204+
172205
func SaveJsonFile(filePath string, v any) error {
173206
var writer bytes.Buffer
174207
encoder := json.NewEncoder(&writer)

0 commit comments

Comments
 (0)