diff --git a/pkg/logger/logger.go b/pkg/logger/logger.go index 648641325..88e6a8c44 100644 --- a/pkg/logger/logger.go +++ b/pkg/logger/logger.go @@ -3,6 +3,7 @@ package logger import ( "fmt" "os" + "path/filepath" "github.com/fatih/color" @@ -25,6 +26,14 @@ type Logger struct { } func NewLogger(logLevel LogLevel, file string) (*Logger, error) { + // If file path is provided, ensure directory exists + if file != "" && file != "/dev/stdout" && file != "/dev/stderr" { + dir := filepath.Dir(file) + if err := os.MkdirAll(dir, 0755); err != nil { + return nil, fmt.Errorf("failed to create log directory: %w", err) + } + } + return &Logger{ LogLevel: logLevel, File: file, @@ -59,41 +68,27 @@ func ParseLogLevel(logLevel string) (LogLevel, error) { } func (l *Logger) log(logColor *color.Color, message string) { - if l.File != "" { - if l.File == "/dev/stdout" { - _, err := logColor.Fprintln(os.Stdout, message) - if err != nil { - color.Red("%s\n", err) - } - } else if l.File == "/dev/stderr" { - _, err := logColor.Fprintln(os.Stderr, message) - if err != nil { - color.Red("%s\n", err) - } + if l.File == "" || l.File == "/dev/stdout" { + if logColor != nil { + fmt.Fprintln(os.Stdout, logColor.Sprint(message)) } else { - f, err := os.OpenFile(l.File, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644) - if err != nil { - color.Red("%s\n", err) - return - } - - defer func(f *os.File) { - err = f.Close() - if err != nil { - color.Red("%s\n", err) - } - }(f) - - _, err = f.Write([]byte(fmt.Sprintf("%s\n", message))) - if err != nil { - color.Red("%s\n", err) - } + fmt.Fprintln(os.Stdout, message) } + return + } + + // Open file in append mode + f, err := os.OpenFile(l.File, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + if err != nil { + fmt.Fprintf(os.Stderr, "Error opening log file: %v\n", err) + return + } + defer f.Close() + + if logColor != nil { + fmt.Fprintln(f, logColor.Sprint(message)) } else { - _, err := logColor.Fprintln(os.Stdout, message) - if err != nil { - color.Red("%s\n", err) - } + fmt.Fprintln(f, message) } } diff --git a/pkg/logger/logger_test.go b/pkg/logger/logger_test.go index f6dccd5b0..2e4367d19 100644 --- a/pkg/logger/logger_test.go +++ b/pkg/logger/logger_test.go @@ -5,6 +5,7 @@ import ( "fmt" "io" "os" + "path/filepath" "testing" "github.com/fatih/color" @@ -147,15 +148,17 @@ func TestLogger_Error(t *testing.T) { } func TestLogger_FileLogging(t *testing.T) { - tempFile := "/tmp/test.log" - defer os.Remove(tempFile) + tmpFile := filepath.Join(os.TempDir(), "test.log") + defer os.Remove(tmpFile) // Clean up after test + + logger, err := NewLogger(LogLevelInfo, tmpFile) + assert.NoError(t, err) - logger, _ := NewLogger(LogLevelInfo, tempFile) logger.Info("File logging test") - data, err := os.ReadFile(tempFile) + content, err := os.ReadFile(tmpFile) assert.NoError(t, err) - assert.Contains(t, string(data), "File logging test") + assert.Contains(t, string(content), "File logging test") } func TestLogger_SetLogLevel(t *testing.T) {