From 198ec95003cf73b142a2cd8380de16bbf47d1408 Mon Sep 17 00:00:00 2001 From: Lasse Gaardsholt Date: Tue, 5 Sep 2023 11:18:05 +0200 Subject: [PATCH] added support for NO_COLOR (#586) * added support for NO_COLOR Signed-off-by: Lasse Gaardsholt * added unit test for `NO_COLOR` Signed-off-by: Lasse Gaardsholt * NO_COLOR can now be set to anything Signed-off-by: Lasse Gaardsholt --------- Signed-off-by: Lasse Gaardsholt --- console.go | 5 +++++ console_test.go | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/console.go b/console.go index 7545b402..6c245bf9 100644 --- a/console.go +++ b/console.go @@ -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) } diff --git a/console_test.go b/console_test.go index c619d96c..e916368a 100644 --- a/console_test.go +++ b/console_test.go @@ -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 := " 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}