Add json format to logs

This commit is contained in:
Juan Carlos Mejías Rodríguez 2019-08-17 16:08:57 -04:00
parent 3dec0205a6
commit 3915fa6b92
3 changed files with 17 additions and 0 deletions

View File

@ -41,6 +41,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `-A, --auth-token` global flag to set Portainer auth token.
- `--config` global flag to set the path to a configuration file. Supported file formats are JSON, TOML, YAML, HCL, envfile and Java properties config files. Defaults to "$HOME/.psu.yaml".
- `-h, --help` global flag to print global help.
- `--log-format` global flag to set log format from "text" and "json". Defaults to "text".
- `-v, --log-level` global flag to set log level from "panic", "faltal", "error", "warning", "info", "debug" and "trace". Defaults to "info".
- `--password` long name for `-p` global flag.
- `-t, --timeout` global flag to set a timeout for requests execution.

View File

@ -6,6 +6,7 @@ ENV PSU_AUTH_TOKEN="" \
PSU_ENDPOINT_GROUP_LIST_FORMAT="" \
PSU_ENDPOINT_LIST_FORMAT="" \
PSU_INSECURE="" \
PSU_LOG_FORMAT="" \
PSU_LOG_LEVEL="" \
PSU_LOGIN_PRINT="" \
PSU_PASSWORD="" \

View File

@ -40,6 +40,7 @@ func init() {
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "Config file. (default \"$HOME/.psu.yaml)\"")
rootCmd.PersistentFlags().StringP("log-level", "v", "info", "Log level. One of trace, debug, info, warning, error, fatal or panic.")
rootCmd.PersistentFlags().String("log-format", "text", "Log format. One of text or json.")
rootCmd.PersistentFlags().BoolP("insecure", "i", false, "Skip Portainer SSL certificate verification.")
rootCmd.PersistentFlags().StringP("url", "l", "", "Portainer url.")
rootCmd.PersistentFlags().StringP("user", "u", "", "Portainer user.")
@ -48,6 +49,7 @@ func init() {
rootCmd.PersistentFlags().DurationP("timeout", "t", 0, "Waiting time before aborting (like 100ms, 30s, 1h20m).")
viper.BindPFlag("config", rootCmd.PersistentFlags().Lookup("config"))
viper.BindPFlag("log-level", rootCmd.PersistentFlags().Lookup("log-level"))
viper.BindPFlag("log-format", rootCmd.PersistentFlags().Lookup("log-format"))
viper.BindPFlag("insecure", rootCmd.PersistentFlags().Lookup("insecure"))
viper.BindPFlag("url", rootCmd.PersistentFlags().Lookup("url"))
viper.BindPFlag("timeout", rootCmd.PersistentFlags().Lookup("timeout"))
@ -95,4 +97,17 @@ func initLogger() {
logrus.SetLevel(logrus.InfoLevel)
}
logrus.SetLevel(logLevel)
switch viper.GetString("log-format") {
case "json":
logrus.SetFormatter(&logrus.JSONFormatter{})
case "text":
logrus.SetFormatter(&logrus.TextFormatter{})
default:
logrus.WithFields(logrus.Fields{
"format": viper.GetString("log-format"),
"implications": `Default text format will be used instead`,
}).Warning("Unknown log format")
logrus.SetFormatter(&logrus.TextFormatter{})
}
}