Melora Hugues
51bc7cb3a0
All checks were successful
continuous-integration/drone/push Build is passing
This commit adds the logrus module, and improves logs handling for the entire program. Error logs are better displayed, and the log level can be set from the configuration file.
62 lines
1.3 KiB
Go
62 lines
1.3 KiB
Go
package config
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/sirupsen/logrus"
|
|
)
|
|
|
|
type TelegramConfig struct {
|
|
ChannelID int64 `json:"channel_id"`
|
|
Token string `json:"token"`
|
|
}
|
|
|
|
type LogConfig struct {
|
|
Level logrus.Level
|
|
}
|
|
|
|
type jsonLogConfig struct {
|
|
Level string `json:"level"`
|
|
}
|
|
|
|
type Config struct {
|
|
Telegram *TelegramConfig
|
|
PollingFrequency time.Duration
|
|
Log *LogConfig
|
|
}
|
|
|
|
type jsonConfig struct {
|
|
Telegram *TelegramConfig `json:"telegram"`
|
|
PollingFrequency int64 `json:"polling_frequency"`
|
|
Log *jsonLogConfig `json:"log"`
|
|
}
|
|
|
|
func parseLevel(lvlStr string) logrus.Level {
|
|
for _, lvl := range logrus.AllLevels {
|
|
if lvl.String() == lvlStr {
|
|
return lvl
|
|
}
|
|
}
|
|
return logrus.InfoLevel
|
|
}
|
|
|
|
func New(filepath string) (*Config, error) {
|
|
content, err := os.ReadFile(filepath)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to read config file %q: %w", filepath, err)
|
|
}
|
|
var jsonConf jsonConfig
|
|
if err := json.Unmarshal(content, &jsonConf); err != nil {
|
|
return nil, fmt.Errorf("failed to parse config file: %w", err)
|
|
}
|
|
return &Config{
|
|
Telegram: jsonConf.Telegram,
|
|
PollingFrequency: time.Duration(jsonConf.PollingFrequency) * time.Second,
|
|
Log: &LogConfig{
|
|
Level: parseLevel(jsonConf.Log.Level),
|
|
},
|
|
}, nil
|
|
}
|