80 lines
1.9 KiB
Go
80 lines
1.9 KiB
Go
package util
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
|
|
"github.com/rs/zerolog"
|
|
"github.com/spf13/cobra"
|
|
)
|
|
|
|
var DefaultLogLevel = zerolog.InfoLevel
|
|
|
|
func Logger(cmd *cobra.Command) *zerolog.Logger {
|
|
return zerolog.Ctx(cmd.Context())
|
|
}
|
|
|
|
func SetLogger(cmd *cobra.Command, logger *zerolog.Logger) {
|
|
cmd.SetContext(logger.WithContext(cmd.Context()))
|
|
}
|
|
|
|
func GetLogLevel(cmd *cobra.Command) *zerolog.Level {
|
|
setLevel, err := GetStrFlagOrEnv(cmd, FLAG_LOG_LEVEL, ENV_LOG_LEVEL)
|
|
if err != nil || setLevel == "" {
|
|
Logger(cmd).Warn().Err(err).
|
|
Str("defaultLogLevel", DefAPILogLevel.String()).
|
|
Msg("no log level set, using default")
|
|
return &DefaultLogLevel
|
|
}
|
|
|
|
level, err := zerolog.ParseLevel(setLevel)
|
|
if err != nil {
|
|
Logger(cmd).Err(err).
|
|
Str("logLevel", setLevel).
|
|
Str("defaultLevel", DefaultLogLevel.String()).
|
|
Msg("Invalid log level, using default")
|
|
level = DefaultLogLevel
|
|
}
|
|
|
|
return &level
|
|
}
|
|
|
|
func GetAPILogLevel(cmd *cobra.Command) *zerolog.Level {
|
|
setLevel, err := GetStrFlagOrEnv(cmd, FLAG_API_LOG_LEVEL, ENV_API_LOG_LEVEL)
|
|
if err != nil || setLevel == "" {
|
|
Logger(cmd).Warn().Err(err).
|
|
Str("defaultLogLevel", DefAPILogLevel.String()).
|
|
Msg("no API log level set, using default")
|
|
return &DefAPILogLevel
|
|
}
|
|
|
|
level, err := zerolog.ParseLevel(setLevel)
|
|
if err != nil {
|
|
Logger(cmd).Err(err).
|
|
Str("logLevel", setLevel).
|
|
Str("defaultLevel", DefAPILogLevel.String()).
|
|
Msg("Invalid API log level, using default")
|
|
level = DefAPILogLevel
|
|
}
|
|
|
|
return &level
|
|
}
|
|
|
|
// If set and not empty, returns the flag value
|
|
// Otherwise, returns the env value, empty or not
|
|
func GetStrFlagOrEnv(cmd *cobra.Command, flagName string, envName string) (string, error) {
|
|
flag, err := cmd.Flags().GetString(flagName)
|
|
if err != nil {
|
|
return "", err
|
|
} else if flag != "" {
|
|
return flag, nil
|
|
}
|
|
|
|
envVal, set := os.LookupEnv(envName)
|
|
if !set {
|
|
return envVal, fmt.Errorf("environment variable %s not set", envName)
|
|
}
|
|
|
|
return envVal, nil
|
|
}
|