Skip to content

Commit

Permalink
added support for NO_COLOR (rs#586)
Browse files Browse the repository at this point in the history
* added support for NO_COLOR

Signed-off-by: Lasse Gaardsholt <lasse.gaardsholt@bestseller.com>

* added unit test for `NO_COLOR`

Signed-off-by: Lasse Gaardsholt <lasse.gaardsholt@bestseller.com>

* NO_COLOR can now be set to anything

Signed-off-by: Lasse Gaardsholt <lasse.gaardsholt@bestseller.com>

---------

Signed-off-by: Lasse Gaardsholt <lasse.gaardsholt@bestseller.com>
  • Loading branch information
Gaardsholt authored and mAdkins committed Mar 2, 2024
1 parent 3d0f810 commit 198ec95
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
5 changes: 5 additions & 0 deletions console.go
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,11 @@ func needsQuote(s string) bool {

// colorize returns the string s wrapped in ANSI code c, unless disabled is true.
func colorize(s interface{}, c int, disabled bool) string {
e := os.Getenv("NO_COLOR")
if e != "" {
disabled = true
}

if disabled {
return fmt.Sprintf("%s", s)
}
Expand Down
19 changes: 19 additions & 0 deletions console_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,25 @@ func TestConsoleWriter(t *testing.T) {
}
})

t.Run("NO_COLOR = true", func(t *testing.T) {
os.Setenv("NO_COLOR", "anything")

buf := &bytes.Buffer{}
w := zerolog.ConsoleWriter{Out: buf}

_, err := w.Write([]byte(`{"level": "warn", "message": "Foobar"}`))
if err != nil {
t.Errorf("Unexpected error when writing output: %s", err)
}

expectedOutput := "<nil> WRN Foobar\n"
actualOutput := buf.String()
if actualOutput != expectedOutput {
t.Errorf("Unexpected output %q, want: %q", actualOutput, expectedOutput)
}
os.Unsetenv("NO_COLOR")
})

t.Run("Write fields", func(t *testing.T) {
buf := &bytes.Buffer{}
w := zerolog.ConsoleWriter{Out: buf, NoColor: true}
Expand Down

0 comments on commit 198ec95

Please sign in to comment.