diff --git a/other/zerolog.go b/other/zerolog.go new file mode 100644 index 0000000..3036a15 --- /dev/null +++ b/other/zerolog.go @@ -0,0 +1,87 @@ +package other + +import ( + "flag" + "io" + "os" + "strings" + + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" +) + +var cliFlagLogLevel = "info" +var cliFlagLogJson = false +var cliFlagLogFile = "" + +func SetupFlags() { + flag.StringVar( + &cliFlagLogLevel, + "loglevel", + "info", + "Set the logging level. Valid values (case insensitive) are: debug, info, warn, error, fatal", + ) + flag.BoolVar( + &cliFlagLogJson, + "logjson", + false, + "Log json objects to stderr instead of nicely formatted ones", + ) + flag.StringVar( + &cliFlagLogFile, + "logfile", + "", + "Set the file to write json formatted log messages to", + ) +} + +func ConfigureLoggingFromCliArgs() { + configLevel() + configOutputs() +} + +func configLevel() { + switch strings.ToLower(*&cliFlagLogLevel) { + case "trace": + zerolog.SetGlobalLevel(zerolog.TraceLevel) + case "debug": + zerolog.SetGlobalLevel(zerolog.DebugLevel) + case "info": + zerolog.SetGlobalLevel(zerolog.InfoLevel) + case "warn": + zerolog.SetGlobalLevel(zerolog.WarnLevel) + case "error": + zerolog.SetGlobalLevel(zerolog.ErrorLevel) + case "fatal": + zerolog.SetGlobalLevel(zerolog.FatalLevel) + default: + zerolog.SetGlobalLevel(zerolog.InfoLevel) + } + log.Info().Str("new-level", *flagLogLevel).Msg("New logging level set") +} + +func configOutputs() { + extraLogWriters := []io.Writer{} + if cliFlagLogFile != "" { + file, err := os.OpenFile(cliFlagLogFile, os.O_APPEND|os.O_CREATE, os.ModeAppend) + if err != nil { + log.Fatal().Err(err).Msg("Failed to open log file") + } + // NOTE: Technically this leaks a file handle + // Shouldn't matter though since the log file should be open until the very end + // Sooooo, eh. Don't care about adding an elaborate system to close the file at the very end. + // OS will do that anyway + extraLogWriters = append(extraLogWriters, file) + } + if !cliFlagLogJson { + console := zerolog.ConsoleWriter{Out: os.Stderr} + log.Logger = zerolog.New(zerolog.MultiLevelWriter(append([]io.Writer{console}, extraLogWriters...)...)). + With(). + Timestamp(). + Logger() + } else { + log.Logger = zerolog.New(zerolog.MultiLevelWriter( + append([]io.Writer{log.Logger}, extraLogWriters...)..., + )).With().Timestamp().Logger() + } +}