Skip to content

Commit

Permalink
Minimize logging API
Browse files Browse the repository at this point in the history
  • Loading branch information
talal committed Aug 25, 2020
1 parent 3e1ef62 commit 8bbd29b
Show file tree
Hide file tree
Showing 5 changed files with 29 additions and 63 deletions.
6 changes: 3 additions & 3 deletions internal/controller/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ func (c *Controller) enqueuePromRule(obj interface{}) {
return
}
if mustParseBool(l[labelOperatorDisable]) {
c.logger.Info("msg", "operator disabled, skipping", "key", key)
c.logger.Debug("msg", "operator disabled, skipping", "key", key)
return
}

Expand Down Expand Up @@ -272,7 +272,7 @@ func (c *Controller) processNextWorkItem() bool {
// Finally, if no errors occurred we Forget this item so it does not
// get queued again until another change happens.
c.workqueue.Forget(obj)
c.logger.Info("msg", "sync successful", "key", key)
c.logger.Debug("msg", "sync successful", "key", key)
return true
}

Expand All @@ -294,7 +294,7 @@ func (c *Controller) syncHandler(key string) error {
case apierrors.IsNotFound(err):
// The resource may no longer exist, in which case we clean up any
// orphaned absent alerts.
c.logger.Info("msg", "PrometheusRule no longer exists", "key", key)
c.logger.Debug("msg", "PrometheusRule no longer exists", "key", key)
err = c.cleanUpOrphanedAbsentAlertsNamespace(namespace, name)
default:
// Requeue object for later processing.
Expand Down
6 changes: 3 additions & 3 deletions internal/controller/prometheusrule.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ OuterLoop:
return errors.Wrap(err, "could not update AbsentPrometheusRule")
}

c.logger.Info("msg", "successfully updated absent metric alert rules",
c.logger.Debug("msg", "successfully updated absent metric alert rules",
"key", fmt.Sprintf("%s/%s", absentPromRule.Namespace, absentPromRule.Name))
return nil
}
Expand Down Expand Up @@ -218,14 +218,14 @@ func (c *Controller) cleanUpOrphanedAbsentAlerts(promRuleName string, absentProm
err = c.promClientset.MonitoringV1().PrometheusRules(absentPromRule.Namespace).
Delete(context.Background(), absentPromRule.Name, metav1.DeleteOptions{})
if err == nil {
c.logger.Info("msg", "successfully deleted orphaned AbsentPrometheusRule",
c.logger.Debug("msg", "successfully deleted orphaned AbsentPrometheusRule",
"key", fmt.Sprintf("%s/%s", absentPromRule.Namespace, absentPromRule.Name))
}
} else {
_, err = c.promClientset.MonitoringV1().PrometheusRules(absentPromRule.Namespace).
Update(context.Background(), absentPromRule.PrometheusRule, metav1.UpdateOptions{})
if err == nil {
c.logger.Info("msg", "successfully cleaned up orphaned absent metric alert rules",
c.logger.Debug("msg", "successfully cleaned up orphaned absent metric alert rules",
"key", fmt.Sprintf("%s/%s", absentPromRule.Namespace, absentPromRule.Name))
}
}
Expand Down
47 changes: 15 additions & 32 deletions internal/log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,24 +15,13 @@
package log

import (
"fmt"
"io"
"os"

gokitlog "github.com/go-kit/kit/log"
gokitlevel "github.com/go-kit/kit/log/level"
)

// Different types of log Level.
const (
LevelAll = "all"
LevelDebug = "debug"
LevelInfo = "info"
LevelWarn = "warn"
LevelError = "error"
LevelNone = "none"
)

// Different types of log Format.
const (
FormatLogfmt = "logfmt"
Expand All @@ -42,61 +31,55 @@ const (
// Logger wraps a go-kit/kit/log.Logger. We use it to define custom methods.
// The Logger is safe for concurrent use by multiple goroutines.
type Logger struct {
gokitlog.Logger
gokitlogger gokitlog.Logger
}

// New returns a new Logger.
func New(w io.Writer, format, lvl string) (*Logger, error) {
func New(w io.Writer, format string, showDebug bool) *Logger {
sw := gokitlog.NewSyncWriter(w)
l := gokitlog.NewLogfmtLogger(sw)
if format == FormatJSON {
l = gokitlog.NewJSONLogger(sw)
}
switch lvl {
case LevelAll:
l = gokitlevel.NewFilter(l, gokitlevel.AllowAll())
case LevelDebug:
if showDebug {
l = gokitlevel.NewFilter(l, gokitlevel.AllowDebug())
case LevelInfo:
} else {
l = gokitlevel.NewFilter(l, gokitlevel.AllowInfo())
case LevelWarn:
l = gokitlevel.NewFilter(l, gokitlevel.AllowWarn())
case LevelError:
l = gokitlevel.NewFilter(l, gokitlevel.AllowError())
case LevelNone:
l = gokitlevel.NewFilter(l, gokitlevel.AllowNone())
default:
return nil, fmt.Errorf("unexpected value for log level: %q, see --help", lvl)
}
l = gokitlog.With(l,
"ts", gokitlog.DefaultTimestampUTC,
"caller", gokitlog.Caller(4),
)
return &Logger{l}, nil
return &Logger{l}
}

// With returns a new contextual logger with keyvals prepended to those passed
// to calls to Log.
func With(l Logger, keyvals ...interface{}) *Logger {
return &Logger{gokitlog.With(l.Logger, keyvals...)}
func With(l *Logger, keyvals ...interface{}) *Logger {
return &Logger{gokitlog.With(l.gokitlogger, keyvals...)}
}

// Debug logs at the debug level.
func (l *Logger) Debug(keyvals ...interface{}) {
gokitlevel.Debug(l.gokitlogger).Log(keyvals...)
}

// Info logs at the info level.
func (l *Logger) Info(keyvals ...interface{}) {
gokitlevel.Info(l.Logger).Log(keyvals...)
gokitlevel.Info(l.gokitlogger).Log(keyvals...)
}

// ErrorWithBackoff logs at the error level and also blocks if it is called
// quite often (1000 times in a second). This behavior is helpful when it used
// in overly tight hot error loops.
func (l *Logger) ErrorWithBackoff(keyvals ...interface{}) {
gokitlevel.Error(l.Logger).Log(keyvals...)
gokitlevel.Error(l.gokitlogger).Log(keyvals...)
errorBackoff()
}

// Fatal logs the given key values and calls os.Exit(1). This should only be
// used by main() function in package main.
func (l *Logger) Fatal(keyvals ...interface{}) {
l.Logger.Log(keyvals...)
l.gokitlogger.Log(keyvals...)
os.Exit(1)
}
31 changes: 7 additions & 24 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,6 @@ var (
)

var (
availableLogLevels = []string{
log.LevelAll,
log.LevelDebug,
log.LevelInfo,
log.LevelWarn,
log.LevelError,
log.LevelNone,
}
availableLogFormats = []string{
log.FormatLogfmt,
log.FormatJSON,
Expand All @@ -59,24 +51,21 @@ var (
)

func main() {
var logLevel, logFormat, kubeconfig, keepLabels string
var showDebug bool
var logFormat, kubeconfig, keepLabels string
flagset := flag.CommandLine
flagset.StringVar(&logLevel, "log-level", log.LevelInfo,
fmt.Sprintf("Log level to use. Possible values: %s", strings.Join(availableLogLevels, ", ")))
flagset.BoolVar(&showDebug, "debug", false, "Print debug level logs")
flagset.StringVar(&logFormat, "log-format", log.FormatLogfmt,
fmt.Sprintf("Log format to use. Possible values: %s", strings.Join(availableLogFormats, ", ")))
flagset.StringVar(&kubeconfig, "kubeconfig", "", "Path to a kubeconfig. Only required if out-of-cluster")
flagset.StringVar(&keepLabels, "keep-labels", strings.Join(defaultKeepLabels, ","),
"A comma separated list of labels to keep from the original alert rule")
if err := flagset.Parse(os.Args[1:]); err != nil {
logFatalf("could not parse flagset: %s", err.Error())
}

logger, err := log.New(os.Stdout, logFormat, logLevel)
if err != nil {
logFatalf(err.Error())
fmt.Fprintf(os.Stderr, "FATAL: could not parse flagset: %s", err.Error())
os.Exit(1)
}

logger := log.New(os.Stdout, logFormat, showDebug)
logger.Info("msg", "starting absent-metrics-operator",
"version", version, "git-commit", commit, "build-date", date)

Expand All @@ -98,7 +87,7 @@ func main() {
if err != nil {
logger.Fatal("msg", "instantiating cluster config failed", "err", err)
}
c, err := controller.New(cfg, controller.DefaultResyncPeriod, r, keepLabelMap, log.With(*logger, "component", "controller"))
c, err := controller.New(cfg, controller.DefaultResyncPeriod, r, keepLabelMap, log.With(logger, "component", "controller"))
if err != nil {
logger.Fatal("msg", "could not instantiate controller", "err", err)
}
Expand All @@ -123,12 +112,6 @@ func main() {
}
}

// logFatalf is used when there is no log.Logger.
func logFatalf(format string, a ...interface{}) {
fmt.Fprintf(os.Stderr, "FATAL: "+format+"\n", a...)
os.Exit(1)
}

func landingPageHandler(logger *log.Logger) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
pageBytes := []byte(`<html>
Expand Down
2 changes: 1 addition & 1 deletion test/suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ var _ = BeforeSuite(func() {
// queued by the controller sequentially and we depend on this behavior in
// our mock assertion.
By("starting controller")
l, err := log.New(GinkgoWriter, log.FormatLogfmt, log.LevelAll)
l := log.New(GinkgoWriter, log.FormatLogfmt, true)
Expect(err).ToNot(HaveOccurred())
kL := map[string]bool{
controller.LabelTier: true,
Expand Down

0 comments on commit 8bbd29b

Please sign in to comment.