From 0aff60e5daf7995890ebc750080032bed543c9ea Mon Sep 17 00:00:00 2001 From: Jack Wotherspoon Date: Mon, 17 Apr 2023 15:04:11 -0400 Subject: [PATCH] fix: allow `--structured-logs` and `--quiet` flags together (#1750) --- cmd/root.go | 9 ++++----- internal/log/log.go | 12 ++++++++++-- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/cmd/root.go b/cmd/root.go index dfeaac0dd..79fe1f0c7 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -342,9 +342,8 @@ func NewCommand(opts ...Option) *Command { } // Handle logger separately from config if c.conf.StructuredLogs { - c.logger, c.cleanup = log.NewStructuredLogger() - } - if c.conf.Quiet { + c.logger, c.cleanup = log.NewStructuredLogger(c.conf.Quiet) + } else if c.conf.Quiet { c.logger = log.NewStdLogger(io.Discard, os.Stderr) } err := parseConfig(c, c.conf, args) @@ -845,9 +844,9 @@ func runSignalWrapper(cmd *Command) (err error) { err = <-shutdownCh switch { case errors.Is(err, errSigInt): - cmd.logger.Errorf("SIGINT signal received. Shutting down...") + cmd.logger.Infof("SIGINT signal received. Shutting down...") case errors.Is(err, errSigTerm): - cmd.logger.Errorf("SIGTERM signal received. Shutting down...") + cmd.logger.Infof("SIGTERM signal received. Shutting down...") default: cmd.logger.Errorf("The proxy has encountered a terminal error: %v", err) } diff --git a/internal/log/log.go b/internal/log/log.go index c44306a58..b88a46685 100644 --- a/internal/log/log.go +++ b/internal/log/log.go @@ -76,7 +76,7 @@ func (l *StructuredLogger) Debugf(format string, v ...interface{}) { } // NewStructuredLogger creates a Logger that logs messages using JSON. -func NewStructuredLogger() (cloudsql.Logger, func() error) { +func NewStructuredLogger(quiet bool) (cloudsql.Logger, func() error) { // Configure structured logs to adhere to LogEntry format // https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry c := zap.NewProductionEncoderConfig() @@ -87,8 +87,16 @@ func NewStructuredLogger() (cloudsql.Logger, func() error) { c.EncodeTime = zapcore.ISO8601TimeEncoder enc := zapcore.NewJSONEncoder(c) + + var syncer zapcore.WriteSyncer + // quiet disables writing to the info log + if quiet { + syncer = zapcore.AddSync(io.Discard) + } else { + syncer = zapcore.Lock(os.Stdout) + } core := zapcore.NewTee( - zapcore.NewCore(enc, zapcore.Lock(os.Stdout), zap.LevelEnablerFunc(func(l zapcore.Level) bool { + zapcore.NewCore(enc, syncer, zap.LevelEnablerFunc(func(l zapcore.Level) bool { // Anything below error, goes to the info log. return l < zapcore.ErrorLevel })),