Skip to content

Commit

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

Signed-off-by: Lasse Gaardsholt <[email protected]>

* added unit test for `NO_COLOR`

Signed-off-by: Lasse Gaardsholt <[email protected]>

* NO_COLOR can now be set to anything

Signed-off-by: Lasse Gaardsholt <[email protected]>

---------

Signed-off-by: Lasse Gaardsholt <[email protected]>
  • Loading branch information
Gaardsholt authored Sep 5, 2023
1 parent b81cc57 commit 1bac5cc
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 @@ -312,6 +312,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 1bac5cc

Please sign in to comment.