-
Notifications
You must be signed in to change notification settings - Fork 2
/
conf.go
105 lines (88 loc) · 2.27 KB
/
conf.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package cmd
import (
"fmt"
"os"
"strconv"
"strings"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/spf13/viper"
)
type LogConf struct {
Level string `mapstructure:"level"`
Type string `mapstructure:"type"`
Caller bool `mapstructure:"caller"`
}
type BotConf struct {
Token string `mapstructure:"token"`
Prefix string `mapstructure:"prefix"`
}
type DatabaseConf struct {
Path string `mapstructure:"path"`
}
type Conf struct {
Port int `mapstructure:"port"`
Log LogConf `mapstructure:"log"`
Bot BotConf `mapstructure:"bot"`
Database DatabaseConf `mapstructure:"database"`
}
// NewLogger will return a new logger
func NewLogger(c *Conf) zerolog.Logger {
// Level parsing
warns := []string{}
lvl, err := zerolog.ParseLevel(c.Log.Level)
if err != nil {
warns = append(warns, fmt.Sprintf("unrecognized log level '%s', fallback to 'info'", c.Log.Level))
zerolog.SetGlobalLevel(zerolog.InfoLevel)
} else {
zerolog.SetGlobalLevel(lvl)
}
// Type parsing
switch c.Log.Type {
case "console":
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
case "json":
break
default:
warns = append(warns, fmt.Sprintf("unrecognized log type '%s', fallback to 'json'", c.Log.Type))
}
// Caller
if c.Log.Caller {
log.Logger = log.With().Caller().Logger()
}
// Log messages with the newly created logger
for _, w := range warns {
log.Warn().Msg(w)
}
return log.Logger
}
// NewConf will parse and return the configuration
func NewConf() (*Conf, error) {
// Environment variables
viper.AutomaticEnv()
viper.SetEnvPrefix("fox")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
// Configuration file
if viper.GetString("conf") != "" {
viper.SetConfigFile(viper.GetString("conf"))
} else {
viper.SetConfigName("conf")
viper.AddConfigPath(".")
viper.AddConfigPath("/config/")
}
viper.ReadInConfig() // nolint: errcheck
conf := &Conf{}
if err := viper.Unmarshal(conf); err != nil {
return conf, fmt.Errorf("unable to unmarshal conf: %w", err)
}
// Override port value for top-level declaration
p := os.Getenv("PORT")
if p != "" {
port, err := strconv.Atoi(p)
if err != nil {
return conf, fmt.Errorf("given port isn't an integer: %w", err)
}
conf.Port = port
}
return conf, nil
}