-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathroot.go
More file actions
100 lines (82 loc) · 2.45 KB
/
root.go
File metadata and controls
100 lines (82 loc) · 2.45 KB
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
package cmd
import (
"fmt"
"os"
"path/filepath"
"runtime/debug"
"time"
"github.com/knadh/koanf/providers/posflag"
"github.com/knadh/koanf/v2"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
)
const (
appName = "riverboat"
prettyFlag = "pretty"
debugFlag = "debug"
)
var k *koanf.Koanf
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: appName,
Short: "A cli for interacting with the riverboat job queue server",
PersistentPreRun: func(cmd *cobra.Command, _ []string) {
err := initCmdFlags(cmd)
cobra.CheckErr(err)
},
}
// 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() {
cobra.CheckErr(rootCmd.Execute())
}
func init() {
k = koanf.New(".") // Create a new koanf instance.
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().Bool(prettyFlag, false, "enable pretty (human readable) logging output")
rootCmd.PersistentFlags().Bool(debugFlag, false, "debug logging output")
}
// initConfig reads in flags set for server startup
// all other configuration is done by the server with koanf
// refer to the README.md for more information
func initConfig() {
if err := initCmdFlags(rootCmd); err != nil {
log.Fatal().Err(err).Msg("error loading config")
}
setupLogging()
}
// initCmdFlags loads the flags from the command line into the koanf instance
func initCmdFlags(cmd *cobra.Command) error {
return k.Load(posflag.Provider(cmd.Flags(), k.Delim(), k), nil)
}
func setupLogging() {
// setup logging with time and app name
log.Logger = zerolog.New(os.Stderr).
With().Timestamp().
Logger().
With().Str("app", appName).
Logger()
// set the log level
zerolog.SetGlobalLevel(zerolog.InfoLevel)
// add additional information to the logger
buildInfo, _ := debug.ReadBuildInfo()
log.Logger = log.Logger.With().
Caller().
Int("pid", os.Getpid()).
Str("go_version", buildInfo.GoVersion).Logger()
// set the log level to debug if the debug flag is set and add additional information
if k.Bool(debugFlag) {
zerolog.SetGlobalLevel(zerolog.DebugLevel)
}
// pretty logging for development
if k.Bool(prettyFlag) {
log.Logger = log.Output(zerolog.ConsoleWriter{
Out: os.Stderr,
TimeFormat: time.RFC3339,
FormatCaller: func(i interface{}) string {
return filepath.Base(fmt.Sprintf("%s", i))
},
})
}
}