diff --git a/internal/cmd/cmd.go b/internal/cmd/cmd.go index 4e4cb8c..158fe4f 100644 --- a/internal/cmd/cmd.go +++ b/internal/cmd/cmd.go @@ -3,10 +3,12 @@ package cmd import ( "context" "errors" + "io" "os" "os/signal" "syscall" + "github.com/mattn/go-isatty" "github.com/jzelinskie/cobrautil/v2" "github.com/jzelinskie/cobrautil/v2/cobrazerolog" "github.com/rs/zerolog" @@ -21,6 +23,25 @@ var ( errParsing = errors.New("parsing error") ) +func init() { + // NOTE: this is mostly to set up logging in the case where + // the command doesn't exist or the construction of the command + // errors out before the PersistentPreRunE setup in the below function. + // It helps keep log output visually consistent for a user even in + // exceptional cases. + var output io.Writer + + if isatty.IsTerminal(os.Stdout.Fd()) { + output = zerolog.ConsoleWriter{Out: os.Stderr} + } else { + output = os.Stderr + } + + l := zerolog.New(output).With().Timestamp().Logger() + + log.Logger = l +} + func Run() { zl := cobrazerolog.New(cobrazerolog.WithPreRunLevel(zerolog.DebugLevel))