Log predefined time formats (#452)

* feat: allow predefined time formats

* refactor(log): use time format constants

* feat(log): time format flag -> time flag

* docs: add formats to help
This commit is contained in:
Maas Lalani 2023-11-08 12:03:49 -05:00 committed by GitHub
parent 3839b8d6e1
commit bf3864e231
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 32 additions and 4 deletions

View file

@ -5,6 +5,7 @@ import (
"math"
"os"
"strings"
"time"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/log"
@ -26,8 +27,36 @@ func (o Options) Run() error {
l.SetPrefix(o.Prefix)
l.SetLevel(-math.MaxInt32) // log all levels
l.SetReportTimestamp(o.Time)
l.SetTimeFormat(o.TimeFormat)
l.SetReportTimestamp(o.Time != "")
timeFormats := map[string]string{
"layout": time.Layout,
"ansic": time.ANSIC,
"unixdate": time.UnixDate,
"rubydate": time.RubyDate,
"rfc822": time.RFC822,
"rfc822z": time.RFC822Z,
"rfc850": time.RFC850,
"rfc1123": time.RFC1123,
"rfc1123z": time.RFC1123Z,
"rfc3339": time.RFC3339,
"rfc3339nano": time.RFC3339Nano,
"kitchen": time.Kitchen,
"stamp": time.Stamp,
"stampmilli": time.StampMilli,
"stampmicro": time.StampMicro,
"stampnano": time.StampNano,
"datetime": "2006-01-02 15:04:05",
"dateonly": "2006-01-02",
"timeonly": "15:04:05",
}
tf, ok := timeFormats[strings.ToLower(o.Time)]
if ok {
l.SetTimeFormat(tf)
} else {
l.SetTimeFormat(o.Time)
}
st := log.DefaultStyles()
defaultColors := map[log.Level]lipgloss.Color{

View file

@ -15,8 +15,7 @@ type Options struct {
Level string `short:"l" help:"The log level to use" enum:"none,debug,info,warn,error,fatal" default:"none"`
Prefix string `help:"Prefix to print before the message"`
Structured bool `short:"s" help:"Use structured logging" xor:"format,structured"`
Time bool `short:"t" help:"Whether to print the time"`
TimeFormat string `help:"The time format to use" default:"15:04:05"`
Time string `short:"t" help:"The time format to use (kitchen, layout, ansic, rfc822, etc...)" default:""`
LevelStyle style.Styles `embed:"" prefix:"level." help:"The style of the level being used" set:"defaultBold=true" envprefix:"GUM_LOG_LEVEL_"` //nolint:staticcheck
TimeStyle style.Styles `embed:"" prefix:"time." help:"The style of the time" envprefix:"GUM_LOG_TIME_"`