From 51290b4f9292d89523bf32797c30ea3b8c579915 Mon Sep 17 00:00:00 2001 From: Noah Petherbridge Date: Tue, 10 Apr 2018 19:09:13 -0700 Subject: [PATCH] No colors for non-interactive shells --- formatter.go | 2 +- golog.go | 9 +++++++++ golog_test.go | 2 ++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/formatter.go b/formatter.go index a355d7d..d7bf82a 100644 --- a/formatter.go +++ b/formatter.go @@ -49,7 +49,7 @@ func (l *Logger) Format(level logLevel, tmpl string, args ...interface{}) string } // Find the theme color to use. - if l.Config.Colors != NoColor { + if interactive && l.Config.Colors != NoColor { var ( primary ThemeColor secondary ThemeColor diff --git a/golog.go b/golog.go index 64836b9..fff201b 100644 --- a/golog.go +++ b/golog.go @@ -1,8 +1,11 @@ package golog import ( + "os" "sync" "text/template" + + "golang.org/x/crypto/ssh/terminal" ) // An internal map of named loggers. This allows for GetLogger() to be called @@ -11,10 +14,16 @@ import ( var ( loggers map[string]*Logger loggerMutex sync.Mutex + + interactive bool // is an interactive shell ) func init() { loggers = map[string]*Logger{} + + // Detect if we're running in an interactive shell, so we can globally + // disable colors when redirecting to a log file. + interactive = terminal.IsTerminal(int(os.Stdout.Fd())) } // Logger stores the configuration for a named logger instance. diff --git a/golog_test.go b/golog_test.go index 239f7a4..1ae9a87 100644 --- a/golog_test.go +++ b/golog_test.go @@ -3,6 +3,8 @@ package golog import "testing" func TestColors(t *testing.T) { + interactive = true // fake an interactive TTY to test color outputs + log := GetLogger("test") // Helper function to emit all the log types.