diff --git a/pkg/instance/instance.go b/pkg/instance/instance.go index dcebef4..e555cae 100644 --- a/pkg/instance/instance.go +++ b/pkg/instance/instance.go @@ -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) +} diff --git a/pkg/instance/logging.go b/pkg/instance/logger.go similarity index 90% rename from pkg/instance/logging.go rename to pkg/instance/logger.go index 5432556..5c993df 100644 --- a/pkg/instance/logging.go +++ b/pkg/instance/logger.go @@ -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)