github.com/criteo/command-launcher@v0.0.0-20230407142452-fb616f546e98/internal/config/logs.go (about) 1 package config 2 3 import ( 4 "fmt" 5 "os" 6 "path/filepath" 7 "time" 8 9 "github.com/criteo/command-launcher/internal/console" 10 log "github.com/sirupsen/logrus" 11 "github.com/spf13/viper" 12 ) 13 14 // Initialize the log file with a the prefix passed as arguments. 15 // 16 // The log level is defined in the configuration settings 17 func InitLog(prefix string) { 18 log.SetFormatter(&log.TextFormatter{ 19 FullTimestamp: true, 20 }) 21 if viper.GetBool(LOG_ENABLED_KEY) { 22 lvl, err := log.ParseLevel(viper.GetString(LOG_LEVEL_KEY)) 23 if err != nil { 24 log.SetLevel(log.FatalLevel) // Log on console the fatal errors 25 console.Warn("Cannot parse the log level") 26 } else { 27 log.SetLevel(lvl) 28 } 29 30 err = createLogsDir() 31 if err != nil { 32 console.Error("cannot create the LOGS dir, err=%v", err) 33 return 34 } 35 36 file, err := os.OpenFile(logFilename(prefix), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) 37 if err == nil { 38 log.SetOutput(file) 39 } else { 40 console.Warn("Cannot create log file") 41 } 42 } 43 log.Debugf("Config file is loaded from %s, reason: %s", configMetadata.File, configMetadata.Reason) 44 } 45 46 func logFilename(prefix string) string { 47 filename := fmt.Sprintf("%s-%s.log", prefix, time.Now().Format("2006-01-02")) 48 return filepath.Join(LogsDir(), filename) 49 }