Skip to content

Commit

Permalink
feat: replace go-kit logger by slog
Browse files Browse the repository at this point in the history
  • Loading branch information
tboerger committed Sep 14, 2024
1 parent 7767f0e commit 43e2a64
Show file tree
Hide file tree
Showing 11 changed files with 73 additions and 103 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions changelog/unreleased/logging-library.md
Original file line number Diff line number Diff line change
@@ -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
9 changes: 3 additions & 6 deletions pkg/action/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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...))
}
39 changes: 13 additions & 26 deletions pkg/action/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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,
Expand All @@ -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,
)

Expand All @@ -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,
)

Expand All @@ -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(
Expand All @@ -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,
)
})
Expand All @@ -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)
Expand All @@ -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,
Expand All @@ -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,
Expand All @@ -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,
Expand Down
11 changes: 2 additions & 9 deletions pkg/command/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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")
}

Expand Down
11 changes: 6 additions & 5 deletions pkg/command/health.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand All @@ -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,
)

Expand All @@ -37,15 +35,18 @@ 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,
)

return err
}

logger.Debug("Health check seems to be fine",
"code", resp.StatusCode,
)

return nil
},
}
Expand Down
40 changes: 19 additions & 21 deletions pkg/command/setup.go
Original file line number Diff line number Diff line change
@@ -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
}
15 changes: 6 additions & 9 deletions pkg/exporter/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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
Expand All @@ -27,15 +26,15 @@ 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)
}

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,
Expand Down Expand Up @@ -103,17 +102,15 @@ 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,
)

c.failures.WithLabelValues("server").Inc()
return
}

level.Debug(c.logger).Log(
"msg", "Fetched servers",
c.logger.Debug("Fetched servers",
"count", len(servers),
)

Expand Down
Loading

0 comments on commit 43e2a64

Please sign in to comment.