From 4aa46a0f3cf9d82457e220eae0cca983d632a7d8 Mon Sep 17 00:00:00 2001 From: FMotalleb Date: Sun, 2 Jun 2024 11:29:00 +0330 Subject: [PATCH] minor: config updated --- .env.example | 10 +++---- .golangci.yml | 1 + cmd/root.go | 45 ++++++++++++++++-------------- config.example.yaml | 4 +-- config/config.go | 55 ++++++++++++------------------------- context/context.go | 1 - context/keys.go | 6 ++-- enums/logger_format_type.go | 20 ++++++++++++++ logger/logger.go | 29 ++++++++++--------- main.go | 5 +--- 10 files changed, 90 insertions(+), 86 deletions(-) create mode 100644 enums/logger_format_type.go diff --git a/.env.example b/.env.example index d112d5b..9fdaff7 100644 --- a/.env.example +++ b/.env.example @@ -1,5 +1,5 @@ -LOG_TIMESTAMP-FORMAT=2006-01-02T15:04:05.000Z -LOG_FORMAT=ansi -LOG_FILE=/var/log/crontab-go.log -LOG_STDOUT=true -LOG_LEVEL=debug +$env.LOG_TIMESTAMP_FORMAT = 2006-01-02T15:04:05.000Z +$env.LOG_FORMAT = ansi +$env.LOG_FILE = /var/log/crontab-go.log +$env.LOG_STDOUT = true +$env.LOG_LEVEL = debug diff --git a/.golangci.yml b/.golangci.yml index 494297c..380e97d 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -19,6 +19,7 @@ linters-settings: linters: disable-all: true enable: + - godoc - bodyclose - dogsled - dupl diff --git a/cmd/root.go b/cmd/root.go index d2faf91..060f3cd 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -1,4 +1,3 @@ -// Package cmd contains cli flags and commands package cmd import ( @@ -14,10 +13,9 @@ import ( var ( cfgFile string - Config *config.Config = &config.Config{} + CFG *config.Config = &config.Config{} ) -// rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{ Use: "crontab-go", Short: "Crontab replacement for containers", @@ -26,13 +24,9 @@ designed to replace the traditional crontab in Docker environments. With its seamless integration and easy-to-use YAML configuration, Cronjob-go simplifies the process of scheduling and managing recurring tasks within your containerized applications.`, - // Uncomment the following line if your bare application - // has an action associated with it: Run: func(cmd *cobra.Command, args []string) {}, } -// Execute adds all child commands to the root command and sets flags appropriately. -// This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() { err := rootCmd.Execute() if err != nil { @@ -43,34 +37,45 @@ func Execute() { func init() { cobra.OnInitialize(initConfig) - // Here you will define your flags and configuration settings. - // Cobra supports persistent flags, which, if defined here, - // will be global for your application. - rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "config file (default is config.yaml)") - - // Cobra also supports local flags, which will only run - // when this action is called directly. - rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") } -// initConfig reads in config file and ENV variables if set. func initConfig() { + viper.BindEnv( + "log_timestamp_format", + "timestamp_format", + ) + viper.BindEnv( + "log_format", + "output_format", + ) + viper.BindEnv( + "log_file", + "output_file", + ) + viper.BindEnv( + "log_stdout", + "print", + ) + viper.BindEnv( + "log_level", + "level", + ) + if cfgFile != "" { - // Use config file from the flag. viper.SetConfigFile(cfgFile) } else { viper.SetConfigName("config") viper.SetConfigType("yaml") + } - viper.AutomaticEnv() // read in environment variables that match + viper.AutomaticEnv() - // If a config file is found, read it in. if err := viper.ReadInConfig(); err == nil { fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed()) } - if err := viper.Unmarshal(Config); err != nil { + if err := viper.Unmarshal(CFG); err != nil { log.Fatalln("Cannot unmarshal the config file", err) } } diff --git a/config.example.yaml b/config.example.yaml index 70646a2..b428e58 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -6,8 +6,8 @@ jobs: description: Backup the production database enabled: true exe: - command: /app/backup.sh - args: ["--help"] + - command: /app/backup.sh + args: ["--help"] scheduler: cron: "0 0 2 * * *" retries: 3 diff --git a/config/config.go b/config/config.go index a49f7f2..2c5c7de 100644 --- a/config/config.go +++ b/config/config.go @@ -1,36 +1,28 @@ -// Package config contains structured representation of config.mapstructure file package config import ( "time" + + "github.com/FMotalleb/crontab-go/enums" ) type ( - // EnvVariables is a map of environment variables that can be used in the configuration. EnvVariables = map[string]string - // JobMetadata is a map of metadata that can be associated with a job. - JobMetadata = map[string]string + JobMetadata = map[string]interface{} - // Config is the main configuration struct for the exporter. Config struct { - Log LogConfig `mapstructure:"log"` - Jobs map[string]JobConfig `mapstructure:"jobs"` - } - - // LogConfig contains the configuration for the logging system. - LogConfig struct { - TimeStampFormat string `mapstructure:"timestamp-format"` - Format string `mapstructure:"format"` - File string `mapstructure:"file"` - Stdout bool `mapstructure:"stdout"` - Level string `mapstructure:"level"` + LogTimestampFormat string `mapstructure:"log_timestamp_format"` + LogFormat enums.LoggerFormatType `mapstructure:"log_format"` + LogFile string `mapstructure:"log_file"` + LogStdout bool `mapstructure:"log_stdout"` + LogLevel string `mapstructure:"log_level"` + Jobs map[string]JobConfig `mapstructure:"jobs"` } - // JobConfig contains the configuration for a single job. JobConfig struct { Description string `mapstructure:"description"` Enabled bool `mapstructure:"enabled"` - Exe JobExe `mapstructure:"exe"` + Exe []Task `mapstructure:"exe"` Scheduler JobScheduler `mapstructure:"scheduler"` Retries int `mapstructure:"retries"` RetryDelay time.Duration `mapstructure:"retry-delay"` @@ -40,34 +32,21 @@ type ( Metadata JobMetadata `mapstructure:"metadata"` } - // JobExe contains the configuration for the executable that a job runs. - JobExe struct { - Command string `mapstructure:"command"` - Args []string `mapstructure:"args"` - } - - // JobScheduler contains the configuration for a job's scheduling. JobScheduler struct { Cron string `mapstructure:"cron"` Interval time.Duration `mapstructure:"interval"` } - // JobHooks contains the configuration for a job's hooks. JobHooks struct { - PreRun []JobHookItem `mapstructure:"pre-run"` - Done []JobHookItem `mapstructure:"done"` - Failed []JobHookItem `mapstructure:"failed"` - } - - // JobHookItem contains the configuration for a single job hook. - JobHookItem struct { - // Webhooks is a list of webhook configurations for the hook. - Webhooks []WebHook `mapstructure:"webhooks"` + Done []Task `mapstructure:"done"` + Failed []Task `mapstructure:"failed"` } - // WebHook contains the configuration for a single webhook. - WebHook struct { - Address string `mapstructure:"address"` + Task struct { + Post string `mapstructure:"get"` + Get string `mapstructure:"post"` + Command string `mapstructure:"command"` + Args []string `mapstructure:"args"` Headers map[string]string `mapstructure:"headers"` Data map[string]any `mapstructure:"data"` } diff --git a/context/context.go b/context/context.go index 866ea08..b011381 100644 --- a/context/context.go +++ b/context/context.go @@ -1,4 +1,3 @@ -// Package context implements basic functionality of context used in the application package context import "context" diff --git a/context/keys.go b/context/keys.go index 8fd6cf4..d7e836a 100644 --- a/context/keys.go +++ b/context/keys.go @@ -1,8 +1,8 @@ package context -type ContextKey = string +type ContextKey string var ( - scope ContextKey = "scope" - logger ContextKey = "logger" + scope ContextKey = ContextKey("scope") + logger ContextKey = ContextKey("logger") ) diff --git a/enums/logger_format_type.go b/enums/logger_format_type.go new file mode 100644 index 0000000..748f032 --- /dev/null +++ b/enums/logger_format_type.go @@ -0,0 +1,20 @@ +package enums + +import "fmt" + +type LoggerFormatType string + +var ( + JsonLogger = LoggerFormatType("json") + AnsiLogger = LoggerFormatType("ansi") + PlainLogger = LoggerFormatType("plain") +) + +func (lf *LoggerFormatType) Validate() error { + switch lf { + case &JsonLogger, &AnsiLogger, &PlainLogger: + return nil + default: + return fmt.Errorf("Given Logger type: `%s`", *lf) + } +} diff --git a/logger/logger.go b/logger/logger.go index 3d939ad..3b064ce 100644 --- a/logger/logger.go +++ b/logger/logger.go @@ -7,16 +7,10 @@ import ( "github.com/sirupsen/logrus" "github.com/FMotalleb/crontab-go/cmd" + "github.com/FMotalleb/crontab-go/enums" ) -type loggerType = string - -var ( - jsonLogger = "json" - ansiLogger = "ansi" - plainLogger = "plain" - log *logrus.Logger = logrus.New() -) +var log *logrus.Logger = logrus.New() // SetupLogger for a section will add the section name to logger's field func SetupLogger(section string) *logrus.Entry { @@ -33,15 +27,24 @@ func SetupLoggerOf(parent logrus.Entry, section string) *logrus.Entry { // InitFromConfig parsed using cmd.Execute() func InitFromConfig() { log = logrus.New() - switch cmd.Config.Log.Format { - case jsonLogger: + if err := cmd.CFG.LogFormat.Validate(); err != nil { + log.Fatal(err) + } + switch cmd.CFG.LogFormat { + case enums.JsonLogger: log.Formatter = &logrus.JSONFormatter{ - TimestampFormat: cmd.Config.Log.TimeStampFormat, + TimestampFormat: cmd.CFG.LogTimestampFormat, } - case ansiLogger: + case enums.AnsiLogger: log.Formatter = &logrus.TextFormatter{ ForceColors: true, - TimestampFormat: cmd.Config.Log.TimeStampFormat, + TimestampFormat: cmd.CFG.LogTimestampFormat, + } + case enums.PlainLogger: + log.Formatter = &logrus.TextFormatter{ + ForceColors: false, + DisableColors: true, + TimestampFormat: cmd.CFG.LogTimestampFormat, } } } diff --git a/main.go b/main.go index be1ddc7..74dca41 100644 --- a/main.go +++ b/main.go @@ -17,7 +17,6 @@ along with this program. If not, see . package main import ( - "context" "encoding/json" "github.com/sirupsen/logrus" @@ -38,8 +37,6 @@ func main() { logger.InitFromConfig() log = *logger.SetupLogger("Crontab-GO") - ctx = context.WithValue(ctx, "log", log) - - j, _ := json.Marshal(cmd.Config) + j, _ := json.Marshal(cmd.CFG) logrus.Infoln(string(j)) }