eia-api-go/cmd/eia-client/internal/util/util_logging.go

80 lines
1.9 KiB
Go
Raw Normal View History

2024-11-16 19:02:46 +00:00
package util
import (
2024-11-19 13:42:18 +00:00
"fmt"
2024-11-16 19:02:46 +00:00
"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 {
2024-11-19 13:42:18 +00:00
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
2024-11-16 19:02:46 +00:00
}
2024-11-19 13:42:18 +00:00
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
2024-11-16 19:02:46 +00:00
}
2024-11-19 13:42:18 +00:00
2024-11-16 19:02:46 +00:00
return &level
}
func GetAPILogLevel(cmd *cobra.Command) *zerolog.Level {
2024-11-19 13:42:18 +00:00
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
2024-11-16 19:02:46 +00:00
}
2024-11-19 13:42:18 +00:00
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
2024-11-16 19:02:46 +00:00
}
2024-11-19 13:42:18 +00:00
2024-11-16 19:02:46 +00:00
return &level
}
2024-11-19 13:42:18 +00:00
// 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
}