Skip to content

Commit

Permalink
feat: LOG_COLOR env to override tty detection (#1508)
Browse files Browse the repository at this point in the history
LOG_COLOR env to override tty detection

eg `LOG_COLOR=1 LOG_LEVEL=trace go test -v ./buildengine -run TestEngine`
  • Loading branch information
gak authored May 17, 2024
1 parent aa733cf commit 9d46ee1
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 4 deletions.
4 changes: 3 additions & 1 deletion internal/log/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,5 +66,7 @@ func ContextWithLogger(ctx context.Context, logger *Logger) context.Context {
}

func ContextWithNewDefaultLogger(ctx context.Context) context.Context {
return ContextWithLogger(ctx, Configure(os.Stderr, Config{Level: Debug}))
// Matches LOG_COLOR in log.Config. This is a special case for the default logger in testing.
color := os.Getenv("LOG_COLOR") != ""
return ContextWithLogger(ctx, Configure(os.Stderr, Config{Level: Debug, Color: color}))
}
3 changes: 2 additions & 1 deletion internal/log/configure.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ type Config struct {
Level Level `help:"Log level." default:"info" env:"LOG_LEVEL"`
JSON bool `help:"Log in JSON format." env:"LOG_JSON"`
Timestamps bool `help:"Include timestamps in text logs." env:"LOG_TIMESTAMPS"`
Color bool `help:"Enable colored output regardless of TTY." env:"LOG_COLOR"`
}

// Configure returns a new logger based on the config.
Expand All @@ -17,7 +18,7 @@ func Configure(w io.Writer, cfg Config) *Logger {
if cfg.JSON {
sink = newJSONSink(w)
} else {
sink = newPlainSink(w, cfg.Timestamps)
sink = newPlainSink(w, cfg.Timestamps, cfg.Color)
}
return New(cfg.Level, sink)
}
6 changes: 4 additions & 2 deletions internal/log/plain.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,11 @@ var colours = map[Level]string{

var _ Sink = (*plainSink)(nil)

func newPlainSink(w io.Writer, logTime bool) *plainSink {
func newPlainSink(w io.Writer, logTime bool, alwaysColor bool) *plainSink {
var isaTTY bool
if f, ok := w.(*os.File); ok {
if alwaysColor {
isaTTY = true
} else if f, ok := w.(*os.File); ok {
isaTTY = isatty.IsTerminal(f.Fd())
}
return &plainSink{
Expand Down

0 comments on commit 9d46ee1

Please sign in to comment.