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 1da736b commit 1e88576
Show file tree
Hide file tree
Showing 13 changed files with 88 additions and 129 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/scw_exporter/issues/104
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/scw_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...))
}
56 changes: 18 additions & 38 deletions pkg/action/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,13 @@ import (
"context"
"fmt"
"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 @@ -23,9 +22,8 @@ import (
)

// Server handles the server sub-command.
func Server(cfg *config.Config, logger log.Logger) error {
level.Info(logger).Log(
"msg", "Launching Scaleway Exporter",
func Server(cfg *config.Config, logger *slog.Logger) error {
logger.Info("Launching Scaleway Exporter",
"version", version.String,
"revision", version.Revision,
"date", version.Date,
Expand All @@ -35,8 +33,7 @@ func Server(cfg *config.Config, logger log.Logger) error {
accessKey, err := config.Value(cfg.Target.AccessKey)

if err != nil {
level.Error(logger).Log(
"msg", "Failed to load access key from file",
logger.Error("Failed to load access key from file",
"err", err,
)

Expand All @@ -46,8 +43,7 @@ func Server(cfg *config.Config, logger log.Logger) error {
secretKey, err := config.Value(cfg.Target.SecretKey)

if err != nil {
level.Error(logger).Log(
"msg", "Failed to load secret key from file",
logger.Error("Failed to load secret key from file",
"err", err,
)

Expand Down Expand Up @@ -88,8 +84,7 @@ func Server(cfg *config.Config, logger log.Logger) error {
)

if err != nil {
level.Error(logger).Log(
"msg", "Failed to parse region",
logger.Error("Failed to parse region",
"err", err,
)

Expand All @@ -107,8 +102,7 @@ func Server(cfg *config.Config, logger log.Logger) error {
)

if err != nil {
level.Error(logger).Log(
"msg", "Failed to parse zone",
logger.Error("Failed to parse zone",
"err", err,
)

Expand All @@ -125,8 +119,7 @@ func Server(cfg *config.Config, logger log.Logger) error {
)

if err != nil {
level.Error(logger).Log(
"msg", "Failed to initialize Scaleway client",
logger.Error("Failed to initialize Scaleway client",
"err", err,
)

Expand All @@ -144,9 +137,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 @@ -163,16 +155,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 @@ -195,7 +185,7 @@ func Server(cfg *config.Config, logger log.Logger) error {
return gr.Run()
}

func handler(cfg *config.Config, logger log.Logger, client *scw.Client) *chi.Mux {
func handler(cfg *config.Config, logger *slog.Logger, client *scw.Client) *chi.Mux {
mux := chi.NewRouter()
mux.Use(middleware.Recoverer(logger))
mux.Use(middleware.RealIP)
Expand All @@ -207,9 +197,7 @@ func handler(cfg *config.Config, logger log.Logger, client *scw.Client) *chi.Mux
}

if cfg.Collector.Dashboard {
level.Debug(logger).Log(
"msg", "Dashboard collector registered",
)
logger.Debug("Dashboard collector registered")

registry.MustRegister(exporter.NewDashboardCollector(
logger,
Expand All @@ -221,9 +209,7 @@ func handler(cfg *config.Config, logger log.Logger, client *scw.Client) *chi.Mux
}

if cfg.Collector.SecurityGroups {
level.Debug(logger).Log(
"msg", "Security group collector registered",
)
logger.Debug("Security group collector registered")

registry.MustRegister(exporter.NewSecurityGroupCollector(
logger,
Expand All @@ -235,9 +221,7 @@ func handler(cfg *config.Config, logger log.Logger, client *scw.Client) *chi.Mux
}

if cfg.Collector.Servers {
level.Debug(logger).Log(
"msg", "Server collector registered",
)
logger.Debug("Server collector registered")

registry.MustRegister(exporter.NewServerCollector(
logger,
Expand All @@ -249,9 +233,7 @@ func handler(cfg *config.Config, logger log.Logger, client *scw.Client) *chi.Mux
}

if cfg.Collector.Snapshots {
level.Debug(logger).Log(
"msg", "Snaptshot collector registered",
)
logger.Debug("Snaptshot collector registered")

registry.MustRegister(exporter.NewSnapshotCollector(
logger,
Expand All @@ -263,9 +245,7 @@ func handler(cfg *config.Config, logger log.Logger, client *scw.Client) *chi.Mux
}

if cfg.Collector.Volumes {
level.Debug(logger).Log(
"msg", "Volume collector registered",
)
logger.Debug("Volume collector registered")

registry.MustRegister(exporter.NewVolumeCollector(
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/scw_exporter/pkg/action"
"github.com/promhippie/scw_exporter/pkg/config"
"github.com/promhippie/scw_exporter/pkg/version"
Expand Down Expand Up @@ -34,18 +33,12 @@ func Run() error {
logger := setupLogger(cfg)

if cfg.Target.AccessKey == "" {
level.Error(logger).Log(
"msg", "Missing required scw.access-key",
)

logger.Error("Missing required scw.access-key")
return fmt.Errorf("missing required scw.access-key")
}

if cfg.Target.SecretKey == "" {
level.Error(logger).Log(
"msg", "Missing required scw.secret-key",
)

logger.Error("Missing required scw.secret-key")
return fmt.Errorf("missing required scw.secret-key")
}

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/scw_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/scw_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
}
12 changes: 5 additions & 7 deletions pkg/exporter/dashboard.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
package exporter

import (
"log/slog"
"time"

"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus"
"github.com/promhippie/scw_exporter/pkg/config"
"github.com/scaleway/scaleway-sdk-go/api/instance/v1"
Expand All @@ -15,7 +14,7 @@ import (
type DashboardCollector struct {
client *scw.Client
instance *instance.API
logger log.Logger
logger *slog.Logger
failures *prometheus.CounterVec
duration *prometheus.HistogramVec
config config.Target
Expand All @@ -40,7 +39,7 @@ type DashboardCollector struct {
}

// NewDashboardCollector returns a new DashboardCollector.
func NewDashboardCollector(logger log.Logger, client *scw.Client, failures *prometheus.CounterVec, duration *prometheus.HistogramVec, cfg config.Target) *DashboardCollector {
func NewDashboardCollector(logger *slog.Logger, client *scw.Client, failures *prometheus.CounterVec, duration *prometheus.HistogramVec, cfg config.Target) *DashboardCollector {
if failures != nil {
failures.WithLabelValues("dashboard").Add(0)
}
Expand All @@ -49,7 +48,7 @@ func NewDashboardCollector(logger log.Logger, client *scw.Client, failures *prom
collector := &DashboardCollector{
client: client,
instance: instance.NewAPI(client),
logger: log.With(logger, "collector", "dashboard"),
logger: logger.With("collector", "dashboard"),
failures: failures,
duration: duration,
config: cfg,
Expand Down Expand Up @@ -209,8 +208,7 @@ func (c *DashboardCollector) Collect(ch chan<- prometheus.Metric) {
c.duration.WithLabelValues("dashboard").Observe(time.Since(now).Seconds())

if err != nil {
level.Error(c.logger).Log(
"msg", "Failed to fetch dashboard",
c.logger.Error("Failed to fetch dashboard",
"zone", zone,
"err", err,
)
Expand Down
Loading

0 comments on commit 1e88576

Please sign in to comment.