fix(util): make `FatalOnError` override `log.Silence`

This commit is contained in:
ThinkChaos 2023-11-21 12:53:39 -05:00
parent b386e22ebe
commit 4e89b44185
4 changed files with 31 additions and 13 deletions

View File

@ -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], ":")

View File

@ -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)

View File

@ -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 {

View File

@ -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)
}
}