From 52ec2b011bcde1e04d61bc54e97a0de634e1c9d1 Mon Sep 17 00:00:00 2001 From: Andrii Shvydkyi <913609+shvydky@users.noreply.github.com> Date: Sun, 8 Dec 2024 14:20:42 +0200 Subject: [PATCH] allow more time formats --- cmd/prettylog/prettylog.go | 51 ++++++++++++++++++++++++++++++-------- 1 file changed, 40 insertions(+), 11 deletions(-) diff --git a/cmd/prettylog/prettylog.go b/cmd/prettylog/prettylog.go index 10d77994..ddc6ab8c 100644 --- a/cmd/prettylog/prettylog.go +++ b/cmd/prettylog/prettylog.go @@ -7,11 +7,41 @@ import ( "fmt" "io" "os" + "sort" + "strings" "time" "github.com/rs/zerolog" ) +var timeFormats map[string]string = map[string]string{ + "default": time.Kitchen, + "ansic": time.ANSIC, + "unix": time.UnixDate, + "rfc822": time.RFC822, + "rfc822z": time.RFC822Z, + "rfc850": time.RFC850, + "rfc1123": time.RFC1123, + "rfc1123z": time.RFC1123Z, + "rfc3339": time.RFC3339, + "rfc3339nano": time.RFC3339Nano, + "stamp": time.Stamp, + "stampmilli": time.StampMilli, + "datetime": time.DateTime, + "timeonly": time.TimeOnly, + "full": time.RFC1123, +} + +func allowedTimeFormats() string { + formats := make([]string, 0, len(timeFormats)) + for k := range timeFormats { + formats = append(formats, k) + } + sort.Strings(formats) + + return strings.Join(formats, ", ") +} + func isInputFromPipe() bool { fileInfo, _ := os.Stdin.Stat() return fileInfo.Mode()&os.ModeCharDevice == 0 @@ -34,27 +64,26 @@ func processInput(reader io.Reader, writer io.Writer) error { return scanner.Err() } -func main() { - timeFormats := map[string]string{ - "default": time.Kitchen, - "full": time.RFC1123, +func getTimeFormat(flagValue string) string { + format, ok := timeFormats[flagValue] + if !ok { + return flagValue } + return format +} + +func main() { timeFormatFlag := flag.String( "time-format", "default", - "Time format, either 'default' or 'full'", + "Time format, one of: "+allowedTimeFormats()+" or a custom golang time format", ) flag.Parse() - timeFormat, ok := timeFormats[*timeFormatFlag] - if !ok { - panic("Invalid time-format provided") - } - writer := zerolog.NewConsoleWriter() - writer.TimeFormat = timeFormat + writer.TimeFormat = getTimeFormat(*timeFormatFlag) if isInputFromPipe() { _ = processInput(os.Stdin, writer)