diff --git a/cmd/root.go b/cmd/root.go index 80abe24d8..eb90c287b 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -88,7 +88,7 @@ func initConfig() { util.FatalOnError("unable to load configuration: ", err) } - log.ConfigureLogger(&cfg.Log) + log.Configure(&cfg.Log) if len(cfg.Ports.HTTP) != 0 { split := strings.Split(cfg.Ports.HTTP[0], ":") diff --git a/cmd/serve.go b/cmd/serve.go index b12e74d14..633af956b 100644 --- a/cmd/serve.go +++ b/cmd/serve.go @@ -40,7 +40,7 @@ func startServer(_ *cobra.Command, _ []string) error { return fmt.Errorf("unable to load configuration: %w", err) } - log.ConfigureLogger(&cfg.Log) + log.Configure(&cfg.Log) signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM) diff --git a/log/logger.go b/log/logger.go index 924b22bf0..c8af0faa0 100644 --- a/log/logger.go +++ b/log/logger.go @@ -9,6 +9,7 @@ import ( "sync" "sync/atomic" + "github.com/creasty/defaults" "github.com/mattn/go-colorable" "github.com/sirupsen/logrus" prefixed "github.com/x-cray/logrus-prefixed-formatter" @@ -49,22 +50,26 @@ type Config struct { Timestamp bool `yaml:"timestamp" default:"true"` } +// DefaultConfig returns a new Config initialized with default values. +func DefaultConfig() *Config { + cfg := new(Config) + + defaults.MustSet(cfg) + + return cfg +} + //nolint:gochecknoinits func init() { if !initDone.CompareAndSwap(false, true) { return } - logger = logrus.New() + newLogger := logrus.New() - defaultConfig := &Config{ - Level: LevelInfo, - Format: FormatTypeText, - Privacy: false, - Timestamp: true, - } + ConfigureLogger(newLogger, DefaultConfig()) - ConfigureLogger(defaultConfig) + logger = newLogger } // Log returns the global logger @@ -94,8 +99,13 @@ func EscapeInput(input string) string { return result } -// ConfigureLogger applies configuration to the global logger -func ConfigureLogger(cfg *Config) { +// Configure applies configuration to the global logger. +func Configure(cfg *Config) { + ConfigureLogger(logger, cfg) +} + +// Configure applies configuration to the given logger. +func ConfigureLogger(logger *logrus.Logger, cfg *Config) { if level, err := logrus.ParseLevel(cfg.Level.String()); err != nil { logger.Fatalf("invalid log level %s %v", cfg.Level, err) } else { diff --git a/util/common.go b/util/common.go index b95ae05bc..1f772e0b3 100644 --- a/util/common.go +++ b/util/common.go @@ -3,6 +3,7 @@ package util import ( "encoding/binary" "fmt" + "io" "net" "path/filepath" "regexp" @@ -159,7 +160,14 @@ func LogOnErrorWithEntry(logEntry *logrus.Entry, message string, err error) { // FatalOnError logs the message only if error is not nil and exits the program execution func FatalOnError(message string, err error) { if err != nil { - log.Log().Fatal(message, err) + logger := log.Log() + + // Make sure the error is printend even if the log has been silenced + if logger.Out == io.Discard { + log.ConfigureLogger(logger, log.DefaultConfig()) + } + + logger.Fatal(message, err) } }