No colors for non-interactive shells

This commit is contained in:
Noah 2018-04-10 19:09:13 -07:00
parent e5fe697fa7
commit 51290b4f92
3 changed files with 12 additions and 1 deletions

View File

@ -49,7 +49,7 @@ func (l *Logger) Format(level logLevel, tmpl string, args ...interface{}) string
} }
// Find the theme color to use. // Find the theme color to use.
if l.Config.Colors != NoColor { if interactive && l.Config.Colors != NoColor {
var ( var (
primary ThemeColor primary ThemeColor
secondary ThemeColor secondary ThemeColor

View File

@ -1,8 +1,11 @@
package golog package golog
import ( import (
"os"
"sync" "sync"
"text/template" "text/template"
"golang.org/x/crypto/ssh/terminal"
) )
// An internal map of named loggers. This allows for GetLogger() to be called // An internal map of named loggers. This allows for GetLogger() to be called
@ -11,10 +14,16 @@ import (
var ( var (
loggers map[string]*Logger loggers map[string]*Logger
loggerMutex sync.Mutex loggerMutex sync.Mutex
interactive bool // is an interactive shell
) )
func init() { func init() {
loggers = map[string]*Logger{} 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. // Logger stores the configuration for a named logger instance.

View File

@ -3,6 +3,8 @@ package golog
import "testing" import "testing"
func TestColors(t *testing.T) { func TestColors(t *testing.T) {
interactive = true // fake an interactive TTY to test color outputs
log := GetLogger("test") log := GetLogger("test")
// Helper function to emit all the log types. // Helper function to emit all the log types.