Move logging to separate struct

This commit is contained in:
2025-10-14 19:32:15 +02:00
parent cf20f304b3
commit ef3478e2a3
2 changed files with 17 additions and 6 deletions

View File

@@ -311,3 +311,7 @@ func (i *Process) IsRemote() bool {
return len(i.options.Nodes) > 0
}
func (i *Process) GetLogs(num_lines int) (string, error) {
return i.logger.GetLogs(num_lines)
}

View File

@@ -6,6 +6,7 @@ import (
"io"
"os"
"strings"
"sync"
"time"
)
@@ -14,6 +15,7 @@ type InstanceLogger struct {
logDir string
logFile *os.File
logFilePath string
mu sync.RWMutex
}
func NewInstanceLogger(name string, logDir string) *InstanceLogger {
@@ -25,6 +27,9 @@ func NewInstanceLogger(name string, logDir string) *InstanceLogger {
// Create creates and opens the log files for stdout and stderr
func (i *InstanceLogger) Create() error {
i.mu.Lock()
defer i.mu.Unlock()
if i.logDir == "" {
return fmt.Errorf("logDir is empty for instance %s", i.name)
}
@@ -52,16 +57,15 @@ func (i *InstanceLogger) Create() error {
}
// GetLogs retrieves the last n lines of logs from the instance
func (i *Process) GetLogs(num_lines int) (string, error) {
func (i *InstanceLogger) GetLogs(num_lines int) (string, error) {
i.mu.RLock()
logFileName := i.logger.logFilePath
i.mu.RUnlock()
defer i.mu.RUnlock()
if logFileName == "" {
return "", fmt.Errorf("log file not created for instance %s", i.Name)
if i.logFilePath == "" {
return "", fmt.Errorf("log file not created for instance %s", i.name)
}
file, err := os.Open(logFileName)
file, err := os.Open(i.logFilePath)
if err != nil {
return "", fmt.Errorf("failed to open log file: %w", err)
}
@@ -95,6 +99,9 @@ func (i *Process) GetLogs(num_lines int) (string, error) {
// closeLogFile closes the log files
func (i *InstanceLogger) Close() {
i.mu.Lock()
defer i.mu.Unlock()
if i.logFile != nil {
timestamp := time.Now().Format("2006-01-02 15:04:05")
fmt.Fprintf(i.logFile, "=== Instance %s stopped at %s ===\n\n", i.name, timestamp)