Forked from flowerinthenight/blog_20190205_use_klog_with_cobra.go
Last active
March 14, 2019 14:44
-
-
Save ursuad/489d9cb5cacae9b95159cf11f5fcc679 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Source: https://flowerinthenight.com/blog/2019/02/05/golang-cobra-klog | |
package main | |
import ( | |
goflag "flag" | |
"github.com/spf13/cobra" | |
flag "github.com/spf13/pflag" | |
"k8s.io/klog" | |
) | |
var ( | |
str = "hello world" | |
rootCmd = &cobra.Command{ | |
Use: "echo", | |
Short: "use klog with cobra", | |
Long: "Use klog together with cobra.", | |
} | |
) | |
func init() { | |
rootCmd.Flags().SortFlags = false | |
rootCmd.AddCommand( | |
RunCmd(), | |
) | |
klog.InitFlags(nil) | |
goflag.Parse() | |
flag.CommandLine.AddGoFlagSet(goflag.CommandLine) | |
} | |
func RunCmd() *cobra.Command { | |
runcmd := &cobra.Command{ | |
Use: "run", | |
Short: "run command", | |
Long: "Run command.", | |
Run: func(cmd *cobra.Command, args []string) { | |
klog.Infof("echo=%v", str) | |
}, | |
} | |
runcmd.Flags().SortFlags = false | |
runcmd.Flags().StringVar(&str, "str", str, "string to print") | |
return runcmd | |
} | |
func main() { | |
if err := rootCmd.Execute(); err != nil { | |
klog.Fatalf("root cmd execute failed, err=%v", err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment