Skip to content
Myr

command.go

This file

Path

log/command.go

149 lines · 3.3 KiB · Go

Last changed by

chore: bump go to 1.25.13 and lint (#1117)Drew Smirnoffbefore adoption4f90464

History of this file

Take it

1// Package log the log command.2package log34import (5	"fmt"6	"math"7	"os"8	"strings"9	"time"1011	"charm.land/lipgloss/v2"12	log "charm.land/log/v2"13)1415// Run is the command-line interface for logging text.16func (o Options) Run() error {17	l := log.New(os.Stderr)1819	if o.File != "" {20		f, err := os.OpenFile(o.File, os.O_CREATE|os.O_WRONLY|os.O_APPEND, os.ModePerm) //nolint:gosec21		if err != nil {22			return fmt.Errorf("error opening file: %w", err)23		}2425		defer f.Close() //nolint:errcheck26		l.SetOutput(f)27	}2829	l.SetPrefix(o.Prefix)30	l.SetLevel(-math.MaxInt32) // log all levels31	l.SetReportTimestamp(o.Time != "")32	if o.MinLevel != "" {33		lvl, err := log.ParseLevel(o.MinLevel)34		if err != nil {35			return err //nolint:wrapcheck36		}37		l.SetLevel(lvl)38	}3940	timeFormats := map[string]string{41		"layout":      time.Layout,42		"ansic":       time.ANSIC,43		"unixdate":    time.UnixDate,44		"rubydate":    time.RubyDate,45		"rfc822":      time.RFC822,46		"rfc822z":     time.RFC822Z,47		"rfc850":      time.RFC850,48		"rfc1123":     time.RFC1123,49		"rfc1123z":    time.RFC1123Z,50		"rfc3339":     time.RFC3339,51		"rfc3339nano": time.RFC3339Nano,52		"kitchen":     time.Kitchen,53		"stamp":       time.Stamp,54		"stampmilli":  time.StampMilli,55		"stampmicro":  time.StampMicro,56		"stampnano":   time.StampNano,57		"datetime":    time.DateTime,58		"dateonly":    time.DateOnly,59		"timeonly":    time.TimeOnly,60	}6162	tf, ok := timeFormats[strings.ToLower(o.Time)]63	if ok {64		l.SetTimeFormat(tf)65	} else {66		l.SetTimeFormat(o.Time)67	}6869	st := log.DefaultStyles()70	lvl := levelToLog[o.Level]71	lvlStyle := o.LevelStyle.ToLipgloss()72	if _, isNoColor := lvlStyle.GetForeground().(lipgloss.NoColor); isNoColor {73		lvlStyle = lvlStyle.Foreground(st.Levels[lvl].GetForeground())74	}7576	st.Levels[lvl] = lvlStyle.77		SetString(strings.ToUpper(lvl.String())).78		Inline(true)7980	st.Timestamp = o.TimeStyle.ToLipgloss().81		Inline(true)82	st.Prefix = o.PrefixStyle.ToLipgloss().83		Inline(true)84	st.Message = o.MessageStyle.ToLipgloss().85		Inline(true)86	st.Key = o.KeyStyle.ToLipgloss().87		Inline(true)88	st.Value = o.ValueStyle.ToLipgloss().89		Inline(true)90	st.Separator = o.SeparatorStyle.ToLipgloss().91		Inline(true)9293	l.SetStyles(st)9495	switch o.Formatter {96	case "json":97		l.SetFormatter(log.JSONFormatter)98	case "logfmt":99		l.SetFormatter(log.LogfmtFormatter)100	case "text":101		l.SetFormatter(log.TextFormatter)102	}103104	var arg0 string105	var args []any106	if len(o.Text) > 0 {107		arg0 = o.Text[0]108	}109110	if len(o.Text) > 1 {111		args = make([]any, len(o.Text[1:]))112		for i, arg := range o.Text[1:] {113			args[i] = arg114		}115	}116117	logger := map[string]logger{118		"none":  {printf: l.Printf, print: l.Print},119		"debug": {printf: l.Debugf, print: l.Debug},120		"info":  {printf: l.Infof, print: l.Info},121		"warn":  {printf: l.Warnf, print: l.Warn},122		"error": {printf: l.Errorf, print: l.Error},123		"fatal": {printf: l.Fatalf, print: l.Fatal},124	}[o.Level]125126	if o.Format {127		logger.printf(arg0, args...)128	} else if o.Structured {129		logger.print(arg0, args...)130	} else {131		logger.print(strings.Join(o.Text, " "))132	}133134	return nil135}136137type logger struct {138	printf func(string, ...any)139	print  func(any, ...any)140}141142var levelToLog = map[string]log.Level{143	"none":  log.Level(math.MaxInt32),144	"debug": log.DebugLevel,145	"info":  log.InfoLevel,146	"warn":  log.WarnLevel,147	"error": log.ErrorLevel,148	"fatal": log.FatalLevel,149}