sys-exporter/config/config.go

85 lines
1.7 KiB
Go
Raw Normal View History

2024-12-02 17:04:50 +00:00
package config
import (
"fmt"
"os"
"github.com/goccy/go-yaml"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
const DefaultConfigFileLocation = "/etc/sys-exporter/config.yml"
type logConfigJson struct {
Level string `yaml:"level"`
}
func (c logConfigJson) logConfig() (LogConfig, error) {
lvl, err := zap.ParseAtomicLevel(c.Level)
if err != nil {
return LogConfig{}, err
}
return LogConfig{
Level: lvl,
}, nil
}
type appConfigJson struct {
2024-12-02 17:37:19 +00:00
LogConfig logConfigJson `yaml:"logging"`
Collectors []string `yaml:"collectors"`
2024-12-02 17:04:50 +00:00
}
func (c appConfigJson) appConfig() (AppConfig, error) {
lc, err := c.LogConfig.logConfig()
if err != nil {
return AppConfig{}, err
}
return AppConfig{
2024-12-02 17:37:19 +00:00
LogConfig: lc,
Collectors: c.Collectors,
2024-12-02 17:04:50 +00:00
}, nil
}
type LogConfig struct {
Level zap.AtomicLevel `yaml:"level"`
}
func (c *LogConfig) ZapConfig() zap.Config {
zapC := zap.Config{
Level: c.Level,
Development: true, // TODO: remove later
Encoding: "console",
EncoderConfig: zap.NewDevelopmentEncoderConfig(),
OutputPaths: []string{"stdout"},
ErrorOutputPaths: []string{"stderr"},
}
zapC.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
return zapC
}
type AppConfig struct {
2024-12-02 17:37:19 +00:00
LogConfig
Collectors []string
2024-12-02 17:04:50 +00:00
}
func New(filepath string) (*AppConfig, error) {
fileContent, err := os.ReadFile(filepath)
if err != nil {
return nil, fmt.Errorf("failed to open config file: %w", err)
}
var v appConfigJson
if err := yaml.Unmarshal(fileContent, &v); err != nil {
return nil, fmt.Errorf("failed to parse config file: %w", err)
}
trueConf, err := v.appConfig()
if err != nil {
return nil, fmt.Errorf("failed to validate config: %w", err)
}
return &trueConf, nil
}