From 7bd7cd3aabda54cd8353c6db8807d239358c7af1 Mon Sep 17 00:00:00 2001 From: Ian Norden Date: Mon, 23 Mar 2020 11:57:36 -0500 Subject: [PATCH] make log file a CLI param; default to stdout if none is provided --- cmd/root.go | 2 ++ main.go | 19 +++++++++++++------ 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/cmd/root.go b/cmd/root.go index b14bf2ca..056329bd 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -110,6 +110,7 @@ func init() { viper.AutomaticEnv() rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file location") + rootCmd.PersistentFlags().String("logfile", "", "file path for logging") rootCmd.PersistentFlags().String("database-name", "vulcanize_public", "database name") rootCmd.PersistentFlags().Int("database-port", 5432, "database port") rootCmd.PersistentFlags().String("database-hostname", "localhost", "database hostname") @@ -122,6 +123,7 @@ func init() { rootCmd.PersistentFlags().String("exporter-name", "exporter", "name of exporter plugin") rootCmd.PersistentFlags().String("log-level", log.InfoLevel.String(), "Log level (trace, debug, info, warn, error, fatal, panic") + viper.BindPFlag("logfile", rootCmd.PersistentFlags().Lookup("logfile")) viper.BindPFlag("database.name", rootCmd.PersistentFlags().Lookup("database-name")) viper.BindPFlag("database.port", rootCmd.PersistentFlags().Lookup("database-port")) viper.BindPFlag("database.hostname", rootCmd.PersistentFlags().Lookup("database-hostname")) diff --git a/main.go b/main.go index f44f218f..7bfdd290 100644 --- a/main.go +++ b/main.go @@ -3,6 +3,8 @@ package main import ( "os" + "github.com/spf13/viper" + "github.com/vulcanize/vulcanizedb/cmd" "github.com/sirupsen/logrus" @@ -12,13 +14,18 @@ func main() { logrus.SetFormatter(&logrus.TextFormatter{ FullTimestamp: true, }) - file, err := os.OpenFile("vulcanizedb.log", - os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) - if err == nil { - logrus.SetOutput(file) + logfile := viper.GetString("logfile") + if logfile != "" { + file, err := os.OpenFile(logfile, + os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) + if err == nil { + logrus.SetOutput(file) + } else { + logrus.SetOutput(os.Stdout) + logrus.Info("Failed to log to file, using default stdout") + } } else { - logrus.Info("Failed to log to file, using default stderr") + logrus.SetOutput(os.Stdout) } - cmd.Execute() }