Add CLICOLOR support

This implement CLICOLOR and CLICOLOR_FORCE check on terminal coloring
as defined in https://bixense.com/clicolors/
This commit is contained in:
Alessio Caiazza 2018-07-13 17:33:25 +02:00
parent d329d24db4
commit 37d651c1f2
1 changed files with 21 additions and 3 deletions

View File

@ -3,6 +3,7 @@ package logrus
import (
"bytes"
"fmt"
"os"
"sort"
"strings"
"sync"
@ -35,6 +36,9 @@ type TextFormatter struct {
// Force disabling colors.
DisableColors bool
// Override coloring based on CLICOLOR and CLICOLOR_FORCE. - https://bixense.com/clicolors/
OverrideColors bool
// Disable timestamp logging. useful when output is redirected to logging
// system that already adds timestamps.
DisableTimestamp bool
@ -78,6 +82,22 @@ func (f *TextFormatter) init(entry *Entry) {
}
}
func (f *TextFormatter) isColored() bool {
isColored := f.ForceColors || f.isTerminal
if f.OverrideColors {
if force, ok := os.LookupEnv("CLICOLOR_FORCE"); ok && force != "0" {
isColored = true
}
if os.Getenv("CLICOLOR") == "0" {
isColored = false
}
}
return isColored && !f.DisableColors
}
// Format renders a single log entry
func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
prefixFieldClashes(entry.Data, f.FieldMap)
@ -100,13 +120,11 @@ func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
f.Do(func() { f.init(entry) })
isColored := (f.ForceColors || f.isTerminal) && !f.DisableColors
timestampFormat := f.TimestampFormat
if timestampFormat == "" {
timestampFormat = defaultTimestampFormat
}
if isColored {
if f.isColored() {
f.printColored(b, entry, keys, timestampFormat)
} else {
if !f.DisableTimestamp {