Skip to content

Commit

Permalink
Merge pull request #416 from PierreF/disable-color
Browse files Browse the repository at this point in the history
Add option to disable color in logs
  • Loading branch information
sgotti committed Jan 26, 2018
2 parents b2decba + 70464d3 commit 5fbf4d9
Show file tree
Hide file tree
Showing 230 changed files with 142,523 additions and 24 deletions.
17 changes: 16 additions & 1 deletion cmd/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ package cmd

import (
"fmt"
"os"

"github.com/mattn/go-isatty"
"github.com/spf13/cobra"
)

Expand All @@ -29,18 +31,23 @@ type CommonConfig struct {
StoreSkipTlsVerify bool
ClusterName string
InitialClusterSpecFile string
LogColor bool
LogLevel string
Debug bool
}

func AddCommonFlags(cmd *cobra.Command, cfg *CommonConfig) {
func AddCommonFlags(cmd *cobra.Command, cfg *CommonConfig, hasLogger bool) {
cmd.PersistentFlags().StringVar(&cfg.StoreBackend, "store-backend", "", "store backend type (etcdv2/etcd, etcdv3 or consul)")
cmd.PersistentFlags().StringVar(&cfg.StoreEndpoints, "store-endpoints", "", "a comma-delimited list of store endpoints (use https scheme for tls communication) (defaults: http://127.0.0.1:2379 for etcd, http://127.0.0.1:8500 for consul)")
cmd.PersistentFlags().StringVar(&cfg.StoreCertFile, "store-cert-file", "", "certificate file for client identification to the store")
cmd.PersistentFlags().StringVar(&cfg.StoreKeyFile, "store-key", "", "private key file for client identification to the store")
cmd.PersistentFlags().BoolVar(&cfg.StoreSkipTlsVerify, "store-skip-tls-verify", false, "skip store certificate verification (insecure!!!)")
cmd.PersistentFlags().StringVar(&cfg.StoreCAFile, "store-ca-file", "", "verify certificates of HTTPS-enabled store servers using this CA bundle")
cmd.PersistentFlags().StringVar(&cfg.ClusterName, "cluster-name", "", "cluster name")
if hasLogger {
cmd.PersistentFlags().BoolVar(&cfg.LogColor, "log-color", false, "enable color in log output (default if attached to a terminal)")
cmd.PersistentFlags().StringVar(&cfg.LogLevel, "log-level", "info", "debug, info (default), warn or error")
}
}

func CheckCommonConfig(cfg *CommonConfig) error {
Expand All @@ -64,3 +71,11 @@ func CheckCommonConfig(cfg *CommonConfig) error {

return nil
}

func IsColorLoggerEnable(cmd *cobra.Command, cfg *CommonConfig) bool {
if cmd.PersistentFlags().Changed("log-color") {
return cfg.LogColor
} else {
return isatty.IsTerminal(os.Stderr.Fd()) || isatty.IsCygwinTerminal(os.Stderr.Fd())
}
}
12 changes: 7 additions & 5 deletions cmd/keeper/keeper.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ type config struct {

uid string
dataDir string
logLevel string
debug bool
pgListenAddress string
pgPort string
Expand All @@ -99,7 +98,7 @@ func init() {
die("cannot get current user: %v", err)
}

cmd.AddCommonFlags(cmdKeeper, &cfg.CommonConfig)
cmd.AddCommonFlags(cmdKeeper, &cfg.CommonConfig, true)

cmdKeeper.PersistentFlags().StringVar(&cfg.uid, "id", "", "keeper uid (must be unique in the cluster and can contain only lower-case letters, numbers and the underscore character). If not provided a random uid will be generated.")
cmdKeeper.PersistentFlags().StringVar(&cfg.uid, "uid", "", "keeper uid (must be unique in the cluster and can contain only lower-case letters, numbers and the underscore character). If not provided a random uid will be generated.")
Expand All @@ -115,7 +114,6 @@ func init() {
cmdKeeper.PersistentFlags().StringVar(&cfg.pgSUUsername, "pg-su-username", user, "postgres superuser user name. Used for keeper managed instance access and pg_rewind based synchronization. It'll be created on db initialization. Defaults to the name of the effective user running stolon-keeper. Must be the same for all keepers.")
cmdKeeper.PersistentFlags().StringVar(&cfg.pgSUPassword, "pg-su-password", "", "postgres superuser password. Only one of --pg-su-password or --pg-su-passwordfile must be provided. Must be the same for all keepers.")
cmdKeeper.PersistentFlags().StringVar(&cfg.pgSUPasswordFile, "pg-su-passwordfile", "", "postgres superuser password file. Only one of --pg-su-password or --pg-su-passwordfile must be provided. Must be the same for all keepers)")
cmdKeeper.PersistentFlags().StringVar(&cfg.logLevel, "log-level", "info", "debug, info (default), warn or error")
cmdKeeper.PersistentFlags().BoolVar(&cfg.debug, "debug", false, "enable debug logging")

cmdKeeper.PersistentFlags().MarkDeprecated("id", "please use --uid")
Expand Down Expand Up @@ -1620,7 +1618,7 @@ func keeper(c *cobra.Command, args []string) {
validAuthMethods := make(map[string]struct{})
validAuthMethods["trust"] = struct{}{}
validAuthMethods["md5"] = struct{}{}
switch cfg.logLevel {
switch cfg.LogLevel {
case "error":
slog.SetLevel(zap.ErrorLevel)
case "warn":
Expand All @@ -1630,11 +1628,15 @@ func keeper(c *cobra.Command, args []string) {
case "debug":
slog.SetLevel(zap.DebugLevel)
default:
die("invalid log level: %v", cfg.logLevel)
die("invalid log level: %v", cfg.LogLevel)
}
if cfg.debug {
slog.SetDebug()
}
if cmd.IsColorLoggerEnable(c, &cfg.CommonConfig) {
log = slog.SColor()
postgresql.SetLogger(log)
}

if cfg.dataDir == "" {
die("data dir required")
Expand Down
20 changes: 13 additions & 7 deletions cmd/proxy/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ type config struct {
listenAddress string
port string
stopListening bool
logLevel string
debug bool

keepAliveIdle int
Expand All @@ -63,12 +62,11 @@ type config struct {
var cfg config

func init() {
cmd.AddCommonFlags(cmdProxy, &cfg.CommonConfig)
cmd.AddCommonFlags(cmdProxy, &cfg.CommonConfig, true)

cmdProxy.PersistentFlags().StringVar(&cfg.listenAddress, "listen-address", "127.0.0.1", "proxy listening address")
cmdProxy.PersistentFlags().StringVar(&cfg.port, "port", "5432", "proxy listening port")
cmdProxy.PersistentFlags().BoolVar(&cfg.stopListening, "stop-listening", true, "stop listening on store error")
cmdProxy.PersistentFlags().StringVar(&cfg.logLevel, "log-level", "info", "debug, info (default), warn or error")
cmdProxy.PersistentFlags().BoolVar(&cfg.debug, "debug", false, "enable debug logging")
cmdProxy.PersistentFlags().IntVar(&cfg.keepAliveIdle, "tcp-keepalive-idle", 0, "set tcp keepalive idle (seconds)")
cmdProxy.PersistentFlags().IntVar(&cfg.keepAliveCount, "tcp-keepalive-count", 0, "set tcp keepalive probe count number")
Expand Down Expand Up @@ -348,7 +346,7 @@ func main() {
}

func proxy(c *cobra.Command, args []string) {
switch cfg.logLevel {
switch cfg.LogLevel {
case "error":
slog.SetLevel(zap.ErrorLevel)
case "warn":
Expand All @@ -358,14 +356,22 @@ func proxy(c *cobra.Command, args []string) {
case "debug":
slog.SetLevel(zap.DebugLevel)
default:
die("invalid log level: %v", cfg.logLevel)
die("invalid log level: %v", cfg.LogLevel)
}
if cfg.debug {
slog.SetDebug()
}
if cmd.IsColorLoggerEnable(c, &cfg.CommonConfig) {
log = slog.SColor()
}
if slog.IsDebug() {
stdlog := slog.StdLog()
pollon.SetLogger(stdlog)
if cmd.IsColorLoggerEnable(c, &cfg.CommonConfig) {
stdlog := slog.StdLogColor()
pollon.SetLogger(stdlog)
} else {
stdlog := slog.StdLog()
pollon.SetLogger(stdlog)
}
}

if err := cmd.CheckCommonConfig(&cfg.CommonConfig); err != nil {
Expand Down
12 changes: 7 additions & 5 deletions cmd/sentinel/sentinel.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,17 +61,15 @@ var cmdSentinel = &cobra.Command{
type config struct {
cmd.CommonConfig
initialClusterSpecFile string
logLevel string
debug bool
}

var cfg config

func init() {
cmd.AddCommonFlags(cmdSentinel, &cfg.CommonConfig)
cmd.AddCommonFlags(cmdSentinel, &cfg.CommonConfig, true)

cmdSentinel.PersistentFlags().StringVar(&cfg.initialClusterSpecFile, "initial-cluster-spec", "", "a file providing the initial cluster specification, used only at cluster initialization, ignored if cluster is already initialized")
cmdSentinel.PersistentFlags().StringVar(&cfg.logLevel, "log-level", "info", "debug, info(default), warn or error")
cmdSentinel.PersistentFlags().BoolVar(&cfg.debug, "debug", false, "enable debug logging (deprecated, use log-level instead)")

cmdSentinel.PersistentFlags().MarkDeprecated("debug", "use --log-level=debug instead")
Expand Down Expand Up @@ -1677,7 +1675,7 @@ func main() {
}

func sentinel(c *cobra.Command, args []string) {
switch cfg.logLevel {
switch cfg.LogLevel {
case "error":
slog.SetLevel(zap.ErrorLevel)
case "warn":
Expand All @@ -1687,11 +1685,15 @@ func sentinel(c *cobra.Command, args []string) {
case "debug":
slog.SetLevel(zap.DebugLevel)
default:
die("invalid log level: %v", cfg.logLevel)
die("invalid log level: %v", cfg.LogLevel)
}
if cfg.debug {
slog.SetDebug()
}
if cmd.IsColorLoggerEnable(c, &cfg.CommonConfig) {
log = slog.SColor()
postgresql.SetLogger(log)
}

if err := cmd.CheckCommonConfig(&cfg.CommonConfig); err != nil {
die(err.Error())
Expand Down
2 changes: 1 addition & 1 deletion cmd/stolonctl/stolonctl.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ type config struct {
var cfg config

func init() {
cmd.AddCommonFlags(cmdStolonCtl, &cfg.CommonConfig)
cmd.AddCommonFlags(cmdStolonCtl, &cfg.CommonConfig, false)
}

var cmdVersion = &cobra.Command{
Expand Down
10 changes: 8 additions & 2 deletions glide.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions glide.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,5 @@ import:
version: 5b3c4e850e90a4cf6a20ebd46c8b32a0a3afcb9e
- package: github.com/golang/protobuf
version: 1e59b77b52bf8e4b449a57e6f79f21226d571845
- package: github.com/mattn/go-isatty
version: v0.0.3
23 changes: 20 additions & 3 deletions pkg/log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@ import (
"go.uber.org/zap/zapcore"
)

var s *zap.SugaredLogger
var (
s *zap.SugaredLogger
sColor *zap.SugaredLogger
)

// default info level
var level = zap.NewAtomicLevelAt(zapcore.InfoLevel)
Expand All @@ -38,13 +41,19 @@ func init() {
ErrorOutputPaths: []string{"stderr"},
}

config.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder

logger, err := config.Build()
if err != nil {
panic(fmt.Errorf("failed to initialize logger: %v", err))
}
s = logger.Sugar()

config.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder

logger, err = config.Build()
if err != nil {
panic(fmt.Errorf("failed to initialize color logger: %v", err))
}
sColor = logger.Sugar()
}

func SetDebug() {
Expand All @@ -66,3 +75,11 @@ func S() *zap.SugaredLogger {
func StdLog() *log.Logger {
return zap.NewStdLog(s.Desugar())
}

func SColor() *zap.SugaredLogger {
return sColor
}

func StdLogColor() *log.Logger {
return zap.NewStdLog(sColor.Desugar())
}
5 changes: 5 additions & 0 deletions pkg/postgresql/postgresql.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import (

_ "github.com/lib/pq"
"github.com/mitchellh/copystructure"
"go.uber.org/zap"
)

const (
Expand Down Expand Up @@ -82,6 +83,10 @@ type InitConfig struct {
DataChecksums bool
}

func SetLogger(l *zap.SugaredLogger) {
log = l
}

func NewManager(pgBinPath string, dataDir string, localConnParams, replConnParams ConnParams, suAuthMethod, suUsername, suPassword, replAuthMethod, replUsername, replPassword string, requestTimeout time.Duration) *Manager {
return &Manager{
pgBinPath: pgBinPath,
Expand Down
9 changes: 9 additions & 0 deletions vendor/github.com/mattn/go-isatty/LICENSE

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions vendor/github.com/mattn/go-isatty/doc.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions vendor/github.com/mattn/go-isatty/isatty_appengine.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 18 additions & 0 deletions vendor/github.com/mattn/go-isatty/isatty_bsd.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 18 additions & 0 deletions vendor/github.com/mattn/go-isatty/isatty_linux.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 19 additions & 0 deletions vendor/github.com/mattn/go-isatty/isatty_linux_ppc64x.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 5fbf4d9

Please sign in to comment.