侧边栏壁纸
博主头像
早日退休博主等级

什么时候不更新了,就是退休去了

  • 累计撰写 43 篇文章
  • 累计创建 6 个标签
  • 累计收到 2 条评论

目 录CONTENT

文章目录

组合 zerolog + cobra + viper + pflag

管理员
2023-09-20 / 0 评论 / 0 点赞 / 87 阅读 / 3190 字

Code

package main

import (
	"fmt"
	"os"

	"github.com/rs/zerolog"
	"github.com/spf13/cobra"
	"github.com/spf13/pflag"
	"github.com/spf13/viper"
)

var (
	ConfigPath string

	LogLevel   string
	JsonOutput bool
)

var log = zerolog.New(zerolog.ConsoleWriter{Out: os.Stdout}).With().Timestamp().Logger()

var rootCmd = &cobra.Command{
	Use:  "test",
	Long: "Sting of the Viper: Getting Cobra and Viper to work together Test",
	PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
		if ConfigPath == "" {
			return nil
		}

		viper.SetConfigFile(ConfigPath)
		if err := viper.ReadInConfig(); err != nil {
			if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
				log.Info().Err(err).Msg("Error reading config file")
				return err
			}
		}

		cmd.Flags().VisitAll(func(f *pflag.Flag) {
			if !f.Changed && viper.IsSet(f.Name) {
				val := viper.Get(f.Name)
				if err := cmd.Flags().Set(f.Name, fmt.Sprintf("%v", val)); err != nil {
					log.Fatal().Err(err).Msg("Could not set flag")
				}
			}
		})

		return nil
	},
	Run: Execute,
}

func Execute(cmd *cobra.Command, args []string) {
	logLevel, err := zerolog.ParseLevel(LogLevel)
	if err != nil {
		log.Fatal().Err(err).Msg("Could not parse log level")
	}

	if JsonOutput {
		log = zerolog.New(os.Stdout).With().Timestamp().Logger()
	}

	zerolog.SetGlobalLevel(logLevel)

	log.Info().
		Str("--log-level", LogLevel).
		Msg("Started with following parameters")

	log.Info().Str("log level", LogLevel).Msg("which log level?")

	fmt.Println("hello")
}

func main() {

	rootCmd.PersistentFlags().StringVar(&ConfigPath, "config", "", "Config file path")
	rootCmd.PersistentFlags().StringVar(&LogLevel, "log-level", "info", "Logging level")
	rootCmd.PersistentFlags().BoolVar(&JsonOutput, "json", false, "Output logs as JSON")

	if err := rootCmd.Execute(); err != nil {
		log.Fatal().Err(err).Msg("Could not start application")
	}

}

效果

☁  test  go run main.go -h
Sting of the Viper: Getting Cobra and Viper to work together Test

Usage:
  test [flags]

Flags:
      --config string      Config file path
  -h, --help               help for test
      --json               Output logs as JSON
      --log-level string   Logging level (default "info")
☁  test  go run main.go
6:30PM INF Started with following parameters --log-level=info
6:30PM INF which log level? log level=info
hello
☁  test  go run main.go --json=false
6:30PM INF Started with following parameters --log-level=info
6:30PM INF which log level? log level=info
hello
☁  test  go run main.go --json=true
{"level":"info","--log-level":"info","time":"2023-09-20T18:30:59+08:00","message":"Started with following parameters"}
{"level":"info","log level":"info","time":"2023-09-20T18:30:59+08:00","message":"which log level?"}
hello
☁  test  go run main.go --json=true --log-level=debug
{"level":"info","--log-level":"debug","time":"2023-09-20T18:31:14+08:00","message":"Started with following parameters"}
{"level":"info","log level":"debug","time":"2023-09-20T18:31:14+08:00","message":"which log level?"}
hello

0

评论区