Browse Source

Remove ANSI colors from podLogs endpoint

Daniel Ramich 4 years ago
parent
commit
8bbc80c24f
2 changed files with 12 additions and 1 deletions
  1. 11 0
      pkg/costmodel/router.go
  2. 1 1
      pkg/log/log.go

+ 11 - 0
pkg/costmodel/router.go

@@ -7,6 +7,7 @@ import (
 	"io/ioutil"
 	"io/ioutil"
 	"net/http"
 	"net/http"
 	"reflect"
 	"reflect"
+	"regexp"
 	"strconv"
 	"strconv"
 	"strings"
 	"strings"
 	"sync"
 	"sync"
@@ -19,6 +20,7 @@ import (
 	"github.com/kubecost/cost-model/pkg/util/timeutil"
 	"github.com/kubecost/cost-model/pkg/util/timeutil"
 	"github.com/kubecost/cost-model/pkg/util/watcher"
 	"github.com/kubecost/cost-model/pkg/util/watcher"
 	"github.com/microcosm-cc/bluemonday"
 	"github.com/microcosm-cc/bluemonday"
+	"github.com/spf13/viper"
 
 
 	v1 "k8s.io/api/core/v1"
 	v1 "k8s.io/api/core/v1"
 
 
@@ -65,6 +67,9 @@ const (
 var (
 var (
 	// gitCommit is set by the build system
 	// gitCommit is set by the build system
 	gitCommit string
 	gitCommit string
+
+	// ANSIRegex matches ANSI escape and colors https://en.wikipedia.org/wiki/ANSI_escape_code
+	ANSIRegex = regexp.MustCompile("\x1b\\[[0-9;]*m")
 )
 )
 
 
 // Accesses defines a singleton application instance, providing access to
 // Accesses defines a singleton application instance, providing access to
@@ -1181,6 +1186,12 @@ func logsFor(c kubernetes.Interface, namespace string, pod string, container str
 		return "", err
 		return "", err
 	}
 	}
 
 
+	// If color is already disabled then we don't need to process the logs
+	// to drop ANSI colors
+	if !viper.GetBool("disable-log-color") {
+		podLogs = ANSIRegex.ReplaceAll(podLogs, []byte{})
+	}
+
 	return string(podLogs), nil
 	return string(podLogs), nil
 }
 }
 
 

+ 1 - 1
pkg/log/log.go

@@ -21,7 +21,7 @@ func InitLogging() {
 	zerolog.TimeFieldFormat = time.RFC3339Nano
 	zerolog.TimeFieldFormat = time.RFC3339Nano
 	// Default to using pretty formatting
 	// Default to using pretty formatting
 	if strings.ToLower(viper.GetString("log-format")) != "json" {
 	if strings.ToLower(viper.GetString("log-format")) != "json" {
-		log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339Nano, NoColor: true})
+		log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339Nano})
 	}
 	}
 
 
 	level, err := zerolog.ParseLevel(viper.GetString("log-level"))
 	level, err := zerolog.ParseLevel(viper.GetString("log-level"))