-
Notifications
You must be signed in to change notification settings - Fork 4
/
root.go
76 lines (61 loc) · 1.65 KB
/
root.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
package cmd
import (
"fmt"
"os"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"github.com/desmos-labs/hephaestus/types"
)
const (
flagLogLevel = "log-level"
flagLogFormat = "log-format"
logFormatJSON = "json"
logFormatText = "text"
)
// RootCmd returns a Cobra command allowing to perform various operations
func RootCmd() *cobra.Command {
rootCmd := &cobra.Command{
Use: types.AppName,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
if _, err := os.Stat(types.DataDir); os.IsNotExist(err) {
_ = os.MkdirAll(types.DataDir, os.ModePerm)
}
return setupLogging(cmd)
},
Short: "Discord bot to interact with a Cosmos chain to perform specific transactions using chat commands",
}
rootCmd.AddCommand(
StartCmd(),
)
rootCmd.PersistentFlags().String(flagLogLevel, zerolog.DebugLevel.String(), "logging level to be used")
rootCmd.PersistentFlags().String(flagLogFormat, logFormatText, "logging format; must be either json or text")
return rootCmd
}
// setupLogging setups the logging for the entire project
func setupLogging(cmd *cobra.Command) error {
// Init logging level
value, err := cmd.Flags().GetString(flagLogLevel)
if err != nil {
return err
}
logLvl, err := zerolog.ParseLevel(value)
if err != nil {
return err
}
zerolog.SetGlobalLevel(logLvl)
// Init logging format
value, err = cmd.Flags().GetString(flagLogFormat)
if err != nil {
return err
}
switch value {
case logFormatJSON:
return nil
case logFormatText:
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
return nil
default:
return fmt.Errorf("invalid logging format: %s", value)
}
}