From 43e2a6410397169715fe563c2b64addd50f30842 Mon Sep 17 00:00:00 2001 From: Thomas Boerger Date: Sat, 14 Sep 2024 13:45:56 +0200 Subject: [PATCH] feat: replace go-kit logger by slog --- Makefile | 2 +- changelog/unreleased/logging-library.md | 7 +++++ pkg/action/metrics.go | 9 ++---- pkg/action/server.go | 39 ++++++++---------------- pkg/command/command.go | 11 ++----- pkg/command/health.go | 11 +++---- pkg/command/setup.go | 40 ++++++++++++------------- pkg/exporter/server.go | 15 ++++------ pkg/exporter/ssh_key.go | 15 ++++------ pkg/exporter/storagebox.go | 18 +++++------ pkg/middleware/recoverer.go | 9 ++---- 11 files changed, 73 insertions(+), 103 deletions(-) create mode 100644 changelog/unreleased/logging-library.md diff --git a/Makefile b/Makefile index 4b2550f..73ab444 100644 --- a/Makefile +++ b/Makefile @@ -16,7 +16,7 @@ endif GOBUILD ?= CGO_ENABLED=0 go build PACKAGES ?= $(shell go list ./...) -SOURCES ?= $(shell find . -name "*.go" -type f) +SOURCES ?= $(shell find . -name "*.go" -type f -not -path ./.devenv/\* -not -path ./.direnv/\*) GENERATE ?= $(PACKAGES) TAGS ?= netgo diff --git a/changelog/unreleased/logging-library.md b/changelog/unreleased/logging-library.md new file mode 100644 index 0000000..15e9141 --- /dev/null +++ b/changelog/unreleased/logging-library.md @@ -0,0 +1,7 @@ +Change: Switch to official logging library + +Since there have been a structured logger part of the Go standard library we +thought it's time to replace the library with that. Be aware that log messages +should change a little bit. + +https://github.com/promhippie/hetzner_exporter/issues/196 diff --git a/pkg/action/metrics.go b/pkg/action/metrics.go index fc0816f..7cecaaf 100644 --- a/pkg/action/metrics.go +++ b/pkg/action/metrics.go @@ -2,9 +2,8 @@ package action import ( "fmt" + "log/slog" - "github.com/go-kit/log" - "github.com/go-kit/log/level" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/collectors" "github.com/promhippie/hetzner_exporter/pkg/version" @@ -49,11 +48,9 @@ func init() { } type promLogger struct { - logger log.Logger + logger *slog.Logger } func (pl promLogger) Println(v ...interface{}) { - level.Error(pl.logger).Log( - "msg", fmt.Sprintln(v...), - ) + pl.logger.Error(fmt.Sprintln(v...)) } diff --git a/pkg/action/server.go b/pkg/action/server.go index 3284ee9..02ae265 100644 --- a/pkg/action/server.go +++ b/pkg/action/server.go @@ -3,14 +3,13 @@ package action import ( "context" "io" + "log/slog" "net/http" "os" "os/signal" "time" "github.com/go-chi/chi/v5" - "github.com/go-kit/log" - "github.com/go-kit/log/level" "github.com/oklog/run" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/prometheus/exporter-toolkit/web" @@ -22,9 +21,8 @@ import ( ) // Server handles the server sub-command. -func Server(cfg *config.Config, logger log.Logger) error { - level.Info(logger).Log( - "msg", "Launching Hetzner Exporter", +func Server(cfg *config.Config, logger *slog.Logger) error { + logger.Info("Launching Hetzner Exporter", "version", version.String, "revision", version.Revision, "date", version.Date, @@ -34,8 +32,7 @@ func Server(cfg *config.Config, logger log.Logger) error { username, err := config.Value(cfg.Target.Username) if err != nil { - level.Error(logger).Log( - "msg", "Failed to load username from file", + logger.Error("Failed to load username from file", "err", err, ) @@ -45,8 +42,7 @@ func Server(cfg *config.Config, logger log.Logger) error { password, err := config.Value(cfg.Target.Password) if err != nil { - level.Error(logger).Log( - "msg", "Failed to load password from file", + logger.Error("Failed to load password from file", "err", err, ) @@ -69,9 +65,8 @@ func Server(cfg *config.Config, logger log.Logger) error { } gr.Add(func() error { - level.Info(logger).Log( - "msg", "Starting metrics server", - "addr", cfg.Server.Addr, + logger.Info("Starting metrics server", + "address", cfg.Server.Addr, ) return web.ListenAndServe( @@ -88,16 +83,14 @@ func Server(cfg *config.Config, logger log.Logger) error { defer cancel() if err := server.Shutdown(ctx); err != nil { - level.Error(logger).Log( - "msg", "Failed to shutdown metrics gracefully", + logger.Error("Failed to shutdown metrics gracefully", "err", err, ) return } - level.Info(logger).Log( - "msg", "Metrics shutdown gracefully", + logger.Info("Metrics shutdown gracefully", "reason", reason, ) }) @@ -120,7 +113,7 @@ func Server(cfg *config.Config, logger log.Logger) error { return gr.Run() } -func handler(cfg *config.Config, logger log.Logger, client *hetzner.Client) *chi.Mux { +func handler(cfg *config.Config, logger *slog.Logger, client *hetzner.Client) *chi.Mux { mux := chi.NewRouter() mux.Use(middleware.Recoverer(logger)) mux.Use(middleware.RealIP) @@ -132,9 +125,7 @@ func handler(cfg *config.Config, logger log.Logger, client *hetzner.Client) *chi } if cfg.Collector.Servers { - level.Debug(logger).Log( - "msg", "Server collector registered", - ) + logger.Debug("Server collector registered") registry.MustRegister(exporter.NewServerCollector( logger, @@ -146,9 +137,7 @@ func handler(cfg *config.Config, logger log.Logger, client *hetzner.Client) *chi } if cfg.Collector.SSHKeys { - level.Debug(logger).Log( - "msg", "SSH key collector registered", - ) + logger.Debug("SSH key collector registered") registry.MustRegister(exporter.NewSSHKeyCollector( logger, @@ -160,9 +149,7 @@ func handler(cfg *config.Config, logger log.Logger, client *hetzner.Client) *chi } if cfg.Collector.Storageboxes { - level.Debug(logger).Log( - "msg", "Storagebox collector registered", - ) + logger.Debug("Storagebox collector registered") registry.MustRegister(exporter.NewStorageboxCollector( logger, diff --git a/pkg/command/command.go b/pkg/command/command.go index a1ddb76..864cefa 100644 --- a/pkg/command/command.go +++ b/pkg/command/command.go @@ -5,7 +5,6 @@ import ( "os" "time" - "github.com/go-kit/log/level" "github.com/promhippie/hetzner_exporter/pkg/action" "github.com/promhippie/hetzner_exporter/pkg/config" "github.com/promhippie/hetzner_exporter/pkg/version" @@ -34,18 +33,12 @@ func Run() error { logger := setupLogger(cfg) if cfg.Target.Username == "" { - level.Error(logger).Log( - "msg", "Missing required hetzner.username", - ) - + logger.Error("Missing required hetzner.username") return fmt.Errorf("missing required hetzner.username") } if cfg.Target.Password == "" { - level.Error(logger).Log( - "msg", "Missing required hetzner.password", - ) - + logger.Error("Missing required hetzner.password") return fmt.Errorf("missing required hetzner.password") } diff --git a/pkg/command/health.go b/pkg/command/health.go index d4e6a07..21067d2 100644 --- a/pkg/command/health.go +++ b/pkg/command/health.go @@ -4,7 +4,6 @@ import ( "fmt" "net/http" - "github.com/go-kit/log/level" "github.com/promhippie/hetzner_exporter/pkg/config" "github.com/urfave/cli/v2" ) @@ -26,8 +25,7 @@ func Health(cfg *config.Config) *cli.Command { ) if err != nil { - level.Error(logger).Log( - "msg", "Failed to request health check", + logger.Error("Failed to request health check", "err", err, ) @@ -37,8 +35,7 @@ func Health(cfg *config.Config) *cli.Command { defer resp.Body.Close() if resp.StatusCode != 200 { - level.Error(logger).Log( - "msg", "Health check seems to be in bad state", + logger.Error("Health check seems to be in bad state", "err", err, "code", resp.StatusCode, ) @@ -46,6 +43,10 @@ func Health(cfg *config.Config) *cli.Command { return err } + logger.Debug("Health check seems to be fine", + "code", resp.StatusCode, + ) + return nil }, } diff --git a/pkg/command/setup.go b/pkg/command/setup.go index c4cc846..8ea755f 100644 --- a/pkg/command/setup.go +++ b/pkg/command/setup.go @@ -1,42 +1,40 @@ package command import ( + "log/slog" "os" "strings" - "github.com/go-kit/log" - "github.com/go-kit/log/level" "github.com/promhippie/hetzner_exporter/pkg/config" ) -func setupLogger(cfg *config.Config) log.Logger { - var logger log.Logger - +func setupLogger(cfg *config.Config) *slog.Logger { if cfg.Logs.Pretty { - logger = log.NewSyncLogger( - log.NewLogfmtLogger(os.Stdout), - ) - } else { - logger = log.NewSyncLogger( - log.NewJSONLogger(os.Stdout), + return slog.New( + slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ + Level: loggerLevel(cfg), + }), ) } + return slog.New( + slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{ + Level: loggerLevel(cfg), + }), + ) +} + +func loggerLevel(cfg *config.Config) slog.Leveler { switch strings.ToLower(cfg.Logs.Level) { case "error": - logger = level.NewFilter(logger, level.AllowError()) + return slog.LevelError case "warn": - logger = level.NewFilter(logger, level.AllowWarn()) + return slog.LevelWarn case "info": - logger = level.NewFilter(logger, level.AllowInfo()) + return slog.LevelInfo case "debug": - logger = level.NewFilter(logger, level.AllowDebug()) - default: - logger = level.NewFilter(logger, level.AllowInfo()) + return slog.LevelDebug } - return log.With( - logger, - "ts", log.DefaultTimestampUTC, - ) + return slog.LevelInfo } diff --git a/pkg/exporter/server.go b/pkg/exporter/server.go index eef17b3..753932a 100644 --- a/pkg/exporter/server.go +++ b/pkg/exporter/server.go @@ -2,10 +2,9 @@ package exporter import ( "context" + "log/slog" "time" - "github.com/go-kit/log" - "github.com/go-kit/log/level" "github.com/prometheus/client_golang/prometheus" "github.com/promhippie/hetzner_exporter/pkg/config" "github.com/promhippie/hetzner_exporter/pkg/internal/hetzner" @@ -14,7 +13,7 @@ import ( // ServerCollector collects metrics about the account in general. type ServerCollector struct { client *hetzner.Client - logger log.Logger + logger *slog.Logger failures *prometheus.CounterVec duration *prometheus.HistogramVec config config.Target @@ -27,7 +26,7 @@ type ServerCollector struct { } // NewServerCollector returns a new ServerCollector. -func NewServerCollector(logger log.Logger, client *hetzner.Client, failures *prometheus.CounterVec, duration *prometheus.HistogramVec, cfg config.Target) *ServerCollector { +func NewServerCollector(logger *slog.Logger, client *hetzner.Client, failures *prometheus.CounterVec, duration *prometheus.HistogramVec, cfg config.Target) *ServerCollector { if failures != nil { failures.WithLabelValues("account").Add(0) } @@ -35,7 +34,7 @@ func NewServerCollector(logger log.Logger, client *hetzner.Client, failures *pro labels := []string{"id", "name", "datacenter"} return &ServerCollector{ client: client, - logger: log.With(logger, "collector", "server"), + logger: logger.With("collector", "server"), failures: failures, duration: duration, config: cfg, @@ -103,8 +102,7 @@ func (c *ServerCollector) Collect(ch chan<- prometheus.Metric) { c.duration.WithLabelValues("server").Observe(time.Since(now).Seconds()) if err != nil { - level.Error(c.logger).Log( - "msg", "Failed to fetch servers", + c.logger.Error("Failed to fetch servers", "err", err, ) @@ -112,8 +110,7 @@ func (c *ServerCollector) Collect(ch chan<- prometheus.Metric) { return } - level.Debug(c.logger).Log( - "msg", "Fetched servers", + c.logger.Debug("Fetched servers", "count", len(servers), ) diff --git a/pkg/exporter/ssh_key.go b/pkg/exporter/ssh_key.go index ca3e8e2..1369175 100644 --- a/pkg/exporter/ssh_key.go +++ b/pkg/exporter/ssh_key.go @@ -2,10 +2,9 @@ package exporter import ( "context" + "log/slog" "time" - "github.com/go-kit/log" - "github.com/go-kit/log/level" "github.com/prometheus/client_golang/prometheus" "github.com/promhippie/hetzner_exporter/pkg/config" "github.com/promhippie/hetzner_exporter/pkg/internal/hetzner" @@ -14,7 +13,7 @@ import ( // SSHKeyCollector collects metrics about the SSH keys. type SSHKeyCollector struct { client *hetzner.Client - logger log.Logger + logger *slog.Logger failures *prometheus.CounterVec duration *prometheus.HistogramVec config config.Target @@ -23,7 +22,7 @@ type SSHKeyCollector struct { } // NewSSHKeyCollector returns a new SSHKeyCollector. -func NewSSHKeyCollector(logger log.Logger, client *hetzner.Client, failures *prometheus.CounterVec, duration *prometheus.HistogramVec, cfg config.Target) *SSHKeyCollector { +func NewSSHKeyCollector(logger *slog.Logger, client *hetzner.Client, failures *prometheus.CounterVec, duration *prometheus.HistogramVec, cfg config.Target) *SSHKeyCollector { if failures != nil { failures.WithLabelValues("ssh_key").Add(0) } @@ -31,7 +30,7 @@ func NewSSHKeyCollector(logger log.Logger, client *hetzner.Client, failures *pro labels := []string{"name", "type", "size", "fingerprint"} return &SSHKeyCollector{ client: client, - logger: log.With(logger, "collector", "ssh_key"), + logger: logger.With("collector", "ssh_key"), failures: failures, duration: duration, config: cfg, @@ -67,8 +66,7 @@ func (c *SSHKeyCollector) Collect(ch chan<- prometheus.Metric) { c.duration.WithLabelValues("ssh_key").Observe(time.Since(now).Seconds()) if err != nil { - level.Error(c.logger).Log( - "msg", "Failed to fetch SSH keys", + c.logger.Error("Failed to fetch SSH keys", "err", err, ) @@ -76,8 +74,7 @@ func (c *SSHKeyCollector) Collect(ch chan<- prometheus.Metric) { return } - level.Debug(c.logger).Log( - "msg", "Fetched SSH keys", + c.logger.Debug("Fetched SSH keys", "count", len(keys), ) diff --git a/pkg/exporter/storagebox.go b/pkg/exporter/storagebox.go index 311e291..6d0daeb 100644 --- a/pkg/exporter/storagebox.go +++ b/pkg/exporter/storagebox.go @@ -2,10 +2,9 @@ package exporter import ( "context" + "log/slog" "time" - "github.com/go-kit/log" - "github.com/go-kit/log/level" "github.com/prometheus/client_golang/prometheus" "github.com/promhippie/hetzner_exporter/pkg/config" "github.com/promhippie/hetzner_exporter/pkg/internal/hetzner" @@ -14,7 +13,7 @@ import ( // StorageboxCollector collects metrics about the SSH keys. type StorageboxCollector struct { client *hetzner.Client - logger log.Logger + logger *slog.Logger failures *prometheus.CounterVec duration *prometheus.HistogramVec config config.Target @@ -34,7 +33,7 @@ type StorageboxCollector struct { } // NewStorageboxCollector returns a new StorageboxCollector. -func NewStorageboxCollector(logger log.Logger, client *hetzner.Client, failures *prometheus.CounterVec, duration *prometheus.HistogramVec, cfg config.Target) *StorageboxCollector { +func NewStorageboxCollector(logger *slog.Logger, client *hetzner.Client, failures *prometheus.CounterVec, duration *prometheus.HistogramVec, cfg config.Target) *StorageboxCollector { if failures != nil { failures.WithLabelValues("storagebox").Add(0) } @@ -42,7 +41,7 @@ func NewStorageboxCollector(logger log.Logger, client *hetzner.Client, failures labels := []string{"id", "name", "location", "login"} return &StorageboxCollector{ client: client, - logger: log.With(logger, "collector", "storagebox"), + logger: logger.With("collector", "storagebox"), failures: failures, duration: duration, config: cfg, @@ -166,8 +165,7 @@ func (c *StorageboxCollector) Collect(ch chan<- prometheus.Metric) { c.duration.WithLabelValues("storagebox").Observe(time.Since(now).Seconds()) if err != nil { - level.Error(c.logger).Log( - "msg", "Failed to fetch storageboxes", + c.logger.Error("Failed to fetch storageboxes", "err", err, ) @@ -175,8 +173,7 @@ func (c *StorageboxCollector) Collect(ch chan<- prometheus.Metric) { return } - level.Debug(c.logger).Log( - "msg", "Fetched storageboxes", + c.logger.Debug("Fetched storageboxes", "count", len(storageboxes), ) @@ -189,8 +186,7 @@ func (c *StorageboxCollector) Collect(ch chan<- prometheus.Metric) { c.duration.WithLabelValues("storagebox").Observe(time.Since(now).Seconds()) if err != nil { - level.Error(c.logger).Log( - "msg", "Failed to fetch storagebox", + c.logger.Error("Failed to fetch storagebox", "number", storagebox.Number, "err", err, ) diff --git a/pkg/middleware/recoverer.go b/pkg/middleware/recoverer.go index 1cc2dab..95f9de1 100644 --- a/pkg/middleware/recoverer.go +++ b/pkg/middleware/recoverer.go @@ -1,21 +1,18 @@ package middleware import ( + "log/slog" "net/http" "runtime/debug" - - "github.com/go-kit/log" - "github.com/go-kit/log/level" ) // Recoverer initializes a recoverer middleware. -func Recoverer(logger log.Logger) func(next http.Handler) http.Handler { +func Recoverer(logger *slog.Logger) func(next http.Handler) http.Handler { return func(next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { defer func() { if rvr := recover(); rvr != nil { - level.Error(logger).Log( - "msg", rvr.(string), + logger.Error(rvr.(string), "trace", string(debug.Stack()), )