1
0
mirror of https://github.com/coreos/prometheus-operator.git synced 2026-02-05 06:45:27 +01:00

chore: reduce code duplication in components

* Share parsing for the logging flags across all binaries.
* Refactor and share the web server implementation between the operator
  and the admission webhook.
* Refactor controller configuration structs to include only the required
  parameters.
* Parse label and field selector arguments early instead of doing it in
  each controller.

Signed-off-by: Simon Pasquier <spasquie@redhat.com>
This commit is contained in:
Simon Pasquier
2023-11-15 10:03:00 +01:00
parent 0eaa3bed46
commit 5e9eed43e4
25 changed files with 959 additions and 843 deletions

View File

@@ -16,6 +16,7 @@
package log
import (
"flag"
"fmt"
"os"
"strings"
@@ -39,9 +40,19 @@ const (
FormatJSON = "json"
)
type Config struct {
Level string
Format string
}
func RegisterFlags(fs *flag.FlagSet, c *Config) {
fs.StringVar(&c.Level, "log-level", "info", fmt.Sprintf("Log level to use. Possible values: %s", strings.Join(AvailableLogLevels, ", ")))
fs.StringVar(&c.Format, "log-format", "logfmt", fmt.Sprintf("Log format to use. Possible values: %s", strings.Join(AvailableLogFormats, ", ")))
}
// NewLogger returns a log.Logger that prints in the provided format at the
// provided level with a UTC timestamp and the caller of the log entry.
func NewLogger(level string, format string) (log.Logger, error) {
func NewLogger(c Config) (log.Logger, error) {
var (
logger log.Logger
lvlOption loglevel.Option
@@ -49,7 +60,7 @@ func NewLogger(level string, format string) (log.Logger, error) {
// For log levels other than debug, the klog verbosity level is 0.
klogv2.ClampLevel(0)
switch strings.ToLower(level) {
switch strings.ToLower(c.Level) {
case LevelAll:
lvlOption = loglevel.AllowAll()
case LevelDebug:
@@ -66,16 +77,16 @@ func NewLogger(level string, format string) (log.Logger, error) {
case LevelNone:
lvlOption = loglevel.AllowNone()
default:
return nil, fmt.Errorf("log log_level %s unknown, %v are possible values", level, AvailableLogLevels)
return nil, fmt.Errorf("log log_level %s unknown, %v are possible values", c.Level, AvailableLogLevels)
}
switch format {
switch c.Format {
case FormatLogFmt:
logger = log.NewLogfmtLogger(log.NewSyncWriter(os.Stdout))
case FormatJSON:
logger = log.NewJSONLogger(log.NewSyncWriter(os.Stdout))
default:
return nil, fmt.Errorf("log format %s unknown, %v are possible values", format, AvailableLogFormats)
return nil, fmt.Errorf("log format %s unknown, %v are possible values", c.Format, AvailableLogFormats)
}
logger = loglevel.NewFilter(logger, lvlOption)