Skip to content

Commit

Permalink
minor: config updated
Browse files Browse the repository at this point in the history
  • Loading branch information
FMotalleb committed Jun 2, 2024
1 parent bf18d41 commit 4aa46a0
Show file tree
Hide file tree
Showing 10 changed files with 90 additions and 86 deletions.
10 changes: 5 additions & 5 deletions .env.example
Original file line number Diff line number Diff line change
@@ -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
1 change: 1 addition & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ linters-settings:
linters:
disable-all: true
enable:
- godoc
- bodyclose
- dogsled
- dupl
Expand Down
45 changes: 25 additions & 20 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// Package cmd contains cli flags and commands
package cmd

import (
Expand All @@ -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",
Expand All @@ -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 {
Expand All @@ -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)
}
}
4 changes: 2 additions & 2 deletions config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
55 changes: 17 additions & 38 deletions config/config.go
Original file line number Diff line number Diff line change
@@ -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"`
Expand All @@ -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"`
}
Expand Down
1 change: 0 additions & 1 deletion context/context.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// Package context implements basic functionality of context used in the application
package context

import "context"
Expand Down
6 changes: 3 additions & 3 deletions context/keys.go
Original file line number Diff line number Diff line change
@@ -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")
)
20 changes: 20 additions & 0 deletions enums/logger_format_type.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
29 changes: 16 additions & 13 deletions logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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,
}
}
}
5 changes: 1 addition & 4 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
package main

import (
"context"
"encoding/json"

"github.com/sirupsen/logrus"
Expand All @@ -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))
}

0 comments on commit 4aa46a0

Please sign in to comment.