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

75 lines
1.9 KiB
Go

package util
import (
"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 {
var level zerolog.Level
var err error
if envLevel := os.Getenv(ENV_LOG_LEVEL); envLevel != "" {
level, err = zerolog.ParseLevel(envLevel)
if err != nil {
Logger(cmd).Err(err).
Str("envLogLevel", envLevel).
Str("envVar", ENV_LOG_LEVEL).
Str("defaultLevel", DefaultLogLevel.String()).
Msg("Invalid log level in environment, using default")
level = DefaultLogLevel
}
}
if flagLevel, err := cmd.Flags().GetString(FLAG_LOG_LEVEL); err == nil {
level, err = zerolog.ParseLevel(flagLevel)
if err != nil {
Logger(cmd).Err(err).
Str("flagLogLevel", flagLevel).
Str("defaultLevel", DefaultLogLevel.String()).
Msg("Invalid log level in command flag, using default")
level = DefaultLogLevel
}
}
return &level
}
func GetAPILogLevel(cmd *cobra.Command) *zerolog.Level {
var level zerolog.Level
var err error
if envLevel := os.Getenv(ENV_API_LOG_LEVEL); envLevel != "" {
level, err = zerolog.ParseLevel(envLevel)
if err != nil {
Logger(cmd).Err(err).
Str("envLogLevel", envLevel).
Str("envVar", ENV_API_LOG_LEVEL).
Str("defaultLevel", DefAPILogLevel.String()).
Msg("Invalid API log level in environment, using default")
level = DefAPILogLevel
}
}
if flagLevel, err := cmd.Flags().GetString(FLAG_API_LOG_LEVEL); err == nil {
level, err = zerolog.ParseLevel(flagLevel)
if err != nil {
Logger(cmd).Err(err).
Str("flagLogLevel", flagLevel).
Str("defaultLevel", DefAPILogLevel.String()).
Msg("Invalid API log level in command flag, using default")
level = DefAPILogLevel
}
}
return &level
}