From dc94f3b1b66f5dff2a446965b618cdb80c638c60 Mon Sep 17 00:00:00 2001 From: Ryota Sakamoto Date: Sun, 16 Jun 2024 19:31:43 +0900 Subject: [PATCH] add debug flag --- cmd/kom/main.go | 11 ----------- pkg/cmd/root.go | 17 +++++++++++++++++ 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/cmd/kom/main.go b/cmd/kom/main.go index 373b433..8451a4c 100644 --- a/cmd/kom/main.go +++ b/cmd/kom/main.go @@ -7,17 +7,6 @@ import ( "github.com/ryota-sakamoto/kubernetes-on-multipass/pkg/cmd" ) -func init() { - logLevel := slog.LevelInfo - if l, b := os.LookupEnv("LOG_LEVEL"); b { - logLevel.UnmarshalText([]byte(l)) - } - - slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{ - Level: logLevel, - }))) -} - func main() { if err := cmd.Execute(); err != nil { slog.Error(err.Error()) diff --git a/pkg/cmd/root.go b/pkg/cmd/root.go index 7aa204a..b9149b8 100644 --- a/pkg/cmd/root.go +++ b/pkg/cmd/root.go @@ -1,6 +1,9 @@ package cmd import ( + "log/slog" + "os" + "github.com/spf13/cobra" ) @@ -12,8 +15,22 @@ var rootCmd = &cobra.Command{ Run: func(cmd *cobra.Command, args []string) { cmd.Help() }, + PersistentPreRun: func(cmd *cobra.Command, args []string) { + logLevel := slog.LevelInfo + if b, _ := cmd.Flags().GetBool("debug"); b { + logLevel = slog.LevelDebug + } + + slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{ + Level: logLevel, + }))) + }, } func Execute() error { return rootCmd.Execute() } + +func init() { + rootCmd.PersistentFlags().BoolP("debug", "", false, "Enable debug mode") +}