move config & logging packages into internal submodules

This commit is contained in:
Piper Pentagram 2024-11-06 16:01:38 -08:00
parent e525b7ff3b
commit 450d425b04
5 changed files with 62 additions and 38 deletions

53
internal/config/config.go Normal file
View file

@ -0,0 +1,53 @@
package config
import (
"fmt"
"github.com/spf13/viper"
)
type AppConfig struct {
LogFile string `yaml:"log_file"`
LogDir string `yaml:"log_dir"`
LogMaxSizeMB int `yaml:"log_max_size_mb"`
LogMaxBackups int `yaml:"log_max_backups"`
LogMaxAgeDays int `yaml:"log_max_age_days"`
LogCompression bool `yaml:"log_compression"`
LogAddSource bool `yaml:"log_add_source"`
}
func Parse() (*AppConfig, error) {
var appConfig *AppConfig
setDefaults()
// automatically populate config with any matching environment vars
viper.SetEnvPrefix("BB")
viper.AutomaticEnv()
viper.SetConfigName("config")
viper.SetConfigType("yaml")
viper.AddConfigPath(".")
err := viper.ReadInConfig()
if err != nil {
return nil, fmt.Errorf("error reading configs: %s", err)
}
err = viper.Unmarshal(&appConfig)
if err != nil {
return nil, fmt.Errorf("error unmarshaling configs: %s", err)
}
return appConfig, nil
}
func setDefaults() {
viper.SetDefault("LogFile", "bingobot.log")
viper.SetDefault("LogDir", "log")
viper.SetDefault("LogMaxSizeMB", 500)
viper.SetDefault("LogMaxBackups", 3)
viper.SetDefault("LogMaxAgeDays", 365)
viper.SetDefault("LogCompression", false)
viper.SetDefault("LogAddSource", true)
}

View file

@ -0,0 +1,40 @@
package config
import (
"testing"
"github.com/spf13/viper"
)
var testConfig string
func init() {
testConfig = `
log_file: "bingobot.log"
log_dir: "log"
log_max_size_mb: 500
log_max_backups: 3
log_max_age_days: 365
log_compression: false
`
// the config file is stored in the project root
viper.AddConfigPath("../..")
}
// test that default configs are working
func TestDefaultConfigs(t *testing.T) {
k := "testdefaultkey"
v := "testdefaultval"
viper.SetDefault(k, v)
_, err := Parse()
if err != nil {
t.Error(err)
}
if viper.GetString(k) != v {
t.Errorf("want %s, got %s", v, viper.GetString(k))
}
}

View file

@ -0,0 +1,42 @@
package logging
import (
"log/slog"
"path/filepath"
"gitlab.com/whom/bingobot/internal/config"
"gopkg.in/natefinch/lumberjack.v2"
)
type Logger struct {
*slog.Logger
}
var (
logger Logger
)
func InitLogger(appConfig *config.AppConfig) Logger {
lj := &lumberjack.Logger{
Filename: filepath.Join(appConfig.LogDir, appConfig.LogFile),
MaxSize: appConfig.LogMaxSizeMB,
MaxBackups: appConfig.LogMaxBackups,
MaxAge: appConfig.LogMaxAgeDays,
Compress: appConfig.LogCompression,
}
logger = Logger{
slog.New(
slog.NewJSONHandler(lj, &slog.HandlerOptions{
AddSource: appConfig.LogAddSource,
}),
),
}
return logger
}
func GetLogger() Logger {
return logger
}