fix: setup logging in server and client commands

Ayman Bagabas created

Change summary

internal/cmd/root.go    |  6 ++++++
internal/cmd/server.go  | 13 ++++---------
internal/config/load.go |  7 -------
3 files changed, 10 insertions(+), 16 deletions(-)

Detailed changes

internal/cmd/root.go 🔗

@@ -24,6 +24,7 @@ import (
 	"github.com/charmbracelet/crush/internal/client"
 	"github.com/charmbracelet/crush/internal/config"
 	"github.com/charmbracelet/crush/internal/event"
+	crushlog "github.com/charmbracelet/crush/internal/log"
 	"github.com/charmbracelet/crush/internal/proto"
 	"github.com/charmbracelet/crush/internal/server"
 	"github.com/charmbracelet/crush/internal/ui/common"
@@ -235,6 +236,11 @@ func connectToServer(cmd *cobra.Command) (*client.Client, *proto.Workspace, func
 		event.Init()
 	}
 
+	if ws.Config != nil {
+		logFile := filepath.Join(ws.Config.Options.DataDirectory, "logs", "crush.log")
+		crushlog.Setup(logFile, debug)
+	}
+
 	cleanup := func() { _ = c.DeleteWorkspace(context.Background(), ws.ID) }
 	return c, ws, cleanup, nil
 }

internal/cmd/server.go 🔗

@@ -7,9 +7,11 @@ import (
 	"log/slog"
 	"os"
 	"os/signal"
+	"path/filepath"
 	"time"
 
 	"github.com/charmbracelet/crush/internal/config"
+	crushlog "github.com/charmbracelet/crush/internal/log"
 	"github.com/charmbracelet/crush/internal/server"
 	"github.com/spf13/cobra"
 )
@@ -39,15 +41,8 @@ var serverCmd = &cobra.Command{
 			return fmt.Errorf("failed to load configuration: %v", err)
 		}
 
-		handler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
-			Level: slog.LevelInfo,
-		})
-		if debug {
-			handler = slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
-				Level: slog.LevelDebug,
-			})
-		}
-		slog.SetDefault(slog.New(handler))
+		logFile := filepath.Join(config.GlobalCacheDir(), "server-"+safeNameRegexp.ReplaceAllString(serverHost, "_"), "crush.log")
+		crushlog.Setup(logFile, debug)
 
 		hostURL, err := server.ParseHostURL(serverHost)
 		if err != nil {

internal/config/load.go 🔗

@@ -22,7 +22,6 @@ import (
 	"github.com/charmbracelet/crush/internal/env"
 	"github.com/charmbracelet/crush/internal/fsext"
 	"github.com/charmbracelet/crush/internal/home"
-	"github.com/charmbracelet/crush/internal/log"
 	powernapConfig "github.com/charmbracelet/x/powernap/pkg/config"
 	"github.com/qjebbs/go-jsons"
 )
@@ -52,12 +51,6 @@ func Load(workingDir, dataDir string, debug bool) (*ConfigStore, error) {
 		cfg.Options.Debug = true
 	}
 
-	// Setup logs
-	log.Setup(
-		filepath.Join(cfg.Options.DataDirectory, "logs", fmt.Sprintf("%s.log", appName)),
-		cfg.Options.Debug,
-	)
-
 	// Load workspace config last so it has highest priority.
 	if wsData, err := os.ReadFile(store.workspacePath); err == nil && len(wsData) > 0 {
 		merged, mergeErr := loadFromBytes(append([][]byte{mustMarshalConfig(cfg)}, wsData))