Skip to content

Commit 43e08d9

Browse files
committed
Implement global verbose flag to set logger verbosity
and if plugin root command already implement a verbose flag pass the flag value down to plugin
1 parent 426b9bb commit 43e08d9

2 files changed

Lines changed: 91 additions & 12 deletions

File tree

docs/plugindev/style_guide.md

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -208,9 +208,6 @@ Available input components:
208208

209209
### Feedback principles
210210

211-
Useful for everyone, critical to the usability of screen-readers and automation
212-
Support verbosity flags (`-v`, `--verbose`).
213-
214211
`--format` to define preferred output
215212

216213
* Useful for humans and machine users, ie table, value, json, csv, yaml, etc

pkg/command/root.go

Lines changed: 91 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,9 @@ import (
3333
"github.com/vmware-tanzu/tanzu-plugin-runtime/plugin"
3434
)
3535

36+
// verbose flag to set the log level
37+
var verbose int
38+
3639
// NewRootCmd creates a root command.
3740
func NewRootCmd() (*cobra.Command, error) { //nolint: gocyclo,funlen
3841
var rootCmd = newRootCmd()
@@ -42,6 +45,9 @@ func NewRootCmd() (*cobra.Command, error) { //nolint: gocyclo,funlen
4245
// Configure defined environment variables found in the config file
4346
cliconfig.ConfigureEnvVariables()
4447

48+
// Initialize the global verbose flag to set the log level verbosity (acceptable values 1 - 9)
49+
rootCmd.PersistentFlags().IntVar(&verbose, "verbose", 0, "number for the log level verbosity(acceptable values 1 - 9)")
50+
4551
rootCmd.AddCommand(
4652
newVersionCmd(),
4753
newPluginCmd(),
@@ -58,6 +64,7 @@ func NewRootCmd() (*cobra.Command, error) { //nolint: gocyclo,funlen
5864
newCEIPParticipationCmd(),
5965
newGenAllDocsCmd(),
6066
)
67+
6168
if _, err := ensureCLIInstanceID(); err != nil {
6269
return nil, errors.Wrap(err, "failed to ensure CLI ID")
6370
}
@@ -240,8 +247,74 @@ func newRootCmd() *cobra.Command {
240247
// silencing usage for now as we are getting double usage from plugins on errors
241248
SilenceUsage: true,
242249
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
243-
// Sets the verbosity of the logger if TANZU_CLI_LOG_LEVEL is set
244-
setLoggerVerbosity()
250+
251+
fmt.Println(args, "args", verbose)
252+
253+
// Validate the verbose flag
254+
if verbose < 0 {
255+
log.Errorf("Invalid value for verbose flag. It should be 0 or greater")
256+
os.Exit(1)
257+
}
258+
259+
// For CLI commands: Default the verbose value to -1 If the flag is not set by user
260+
// For Plugin commands: This won't be executed since flags are not parsed by cli but send to plugin as args
261+
if !cmd.Flags().Changed("verbose") {
262+
verbose = -1
263+
}
264+
265+
/**
266+
Manually parse the flags when plugin command is triggered
267+
1. For CLI commands; all flags have been parsed and removed from the list of args and this loop will not run
268+
2. For Plugin commands; Since CLI doesn't parse args and sends all args to plugin this loop will run to verify if verbose flag is set by the user and then passes to plugin.
269+
*/
270+
for i := 0; i < len(args); i++ {
271+
arg := args[i]
272+
if arg == "--verbose" {
273+
if i+1 < len(args) {
274+
nextArg := args[i+1]
275+
// Check if the next argument is another flag
276+
if strings.HasPrefix(nextArg, "-") {
277+
log.Errorf("Missing value for verbose flag")
278+
os.Exit(1)
279+
}
280+
// Try to convert the next argument to an integer
281+
if v, err := strconv.Atoi(nextArg); err == nil {
282+
verbose = v
283+
// If it's not an integer, check if it's a boolean
284+
} else if v, err := strconv.ParseBool(nextArg); err == nil {
285+
// TODO: Determine what verbose value need to set when plugin verbose is boolean true or false
286+
if v {
287+
verbose = 3 // Default log level is 3
288+
} else {
289+
verbose = 0
290+
}
291+
} else {
292+
log.Errorf("Invalid value for verbose flag: %v\n", err)
293+
os.Exit(1)
294+
}
295+
// Skip the next argument
296+
i++
297+
} else {
298+
log.Errorf("Missing value for verbose flag")
299+
os.Exit(1)
300+
}
301+
}
302+
}
303+
304+
// Sets the verbosity of the logger
305+
306+
log.Infof("verbose %v", verbose)
307+
setLoggerVerbosity(verbose)
308+
309+
//TODO: Remove test logs
310+
log.Info("I am level default")
311+
log.V(0).Info("I am level 0")
312+
log.V(1).Info("I am level 1")
313+
log.V(2).Info("I am level 2")
314+
log.V(3).Info("I am level 3")
315+
log.V(4).Info("I am level 4")
316+
log.V(5).Info("I am level 5")
317+
log.V(6).Info("I am level 6")
245318

246319
// Ensure mutual exclusion in current contexts just in case if any plugins with old
247320
// plugin-runtime sets k8s context as current when tanzu context is already set as current
@@ -291,13 +364,22 @@ func newRootCmd() *cobra.Command {
291364
}
292365

293366
// setLoggerVerbosity sets the verbosity of the logger if TANZU_CLI_LOG_LEVEL is set
294-
func setLoggerVerbosity() {
295-
// Configure the log level if env variable TANZU_CLI_LOG_LEVEL is set
296-
logLevel := os.Getenv(log.EnvTanzuCLILogLevel)
297-
if logLevel != "" {
298-
logValue, err := strconv.ParseInt(logLevel, 10, 32)
299-
if err == nil {
300-
log.SetVerbosity(int32(logValue))
367+
func setLoggerVerbosity(verbosity int) {
368+
// If verbose global flag is passed set the log level verbosity if not then check if env variable TANZU_CLI_LOG_LEVEL is set
369+
if verbosity >= 0 {
370+
// Set the log level verbosity with the verbosity value
371+
log.SetVerbosity(int32(verbosity))
372+
373+
// Set the TANZU_CLI_LOG_LEVEL env with the verbosity value
374+
_ = os.Setenv(log.EnvTanzuCLILogLevel, strconv.Itoa(verbosity))
375+
} else {
376+
// Configure the log level if env variable TANZU_CLI_LOG_LEVEL is set
377+
logLevel := os.Getenv(log.EnvTanzuCLILogLevel)
378+
if logLevel != "" {
379+
logValue, err := strconv.ParseInt(logLevel, 10, 32)
380+
if err == nil {
381+
log.SetVerbosity(int32(logValue))
382+
}
301383
}
302384
}
303385
}

0 commit comments

Comments
 (0)