Skip to content

Commit

Permalink
fix: allow --structured-logs and --quiet flags together (#1750)
Browse files Browse the repository at this point in the history
  • Loading branch information
jackwotherspoon authored Apr 17, 2023
1 parent cca5fcf commit 0aff60e
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 7 deletions.
9 changes: 4 additions & 5 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
}
Expand Down
12 changes: 10 additions & 2 deletions internal/log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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
})),
Expand Down

0 comments on commit 0aff60e

Please sign in to comment.