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 authored and renovate[bot] committed Sep 14, 2024
1 parent 2b12231 commit eee0476
Show file tree
Hide file tree
Showing 9 changed files with 60 additions and 79 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/dockerhub_exporter/issues/186
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/dockerhub_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...))
}
34 changes: 12 additions & 22 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 DockerHub Exporter",
func Server(cfg *config.Config, logger *slog.Logger) error {
logger.Info("Launching DockerHub 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 @@ -59,8 +55,7 @@ func Server(cfg *config.Config, logger log.Logger) error {
)

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

Expand All @@ -78,9 +73,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 @@ -97,16 +91,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 @@ -129,7 +121,7 @@ func Server(cfg *config.Config, logger log.Logger) error {
return gr.Run()
}

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

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

registry.MustRegister(exporter.NewRepoCollector(
logger,
Expand Down
6 changes: 1 addition & 5 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/dockerhub_exporter/pkg/action"
"github.com/promhippie/dockerhub_exporter/pkg/config"
"github.com/promhippie/dockerhub_exporter/pkg/version"
Expand Down Expand Up @@ -36,10 +35,7 @@ func Run() error {
if len(cfg.Target.Orgs.Value()) == 0 &&
len(cfg.Target.Users.Value()) == 0 &&
len(cfg.Target.Repos.Value()) == 0 {
level.Error(logger).Log(
"msg", "Missing required org, user or repo",
)

logger.Error("Missing required org, user or repo")
return fmt.Errorf("missing required org, user or repo")
}

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/dockerhub_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/dockerhub_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
}
21 changes: 8 additions & 13 deletions pkg/exporter/repo.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/dockerhub_exporter/pkg/config"
"github.com/promhippie/dockerhub_exporter/pkg/internal/dockerhub"
Expand All @@ -14,7 +13,7 @@ import (
// RepoCollector collects metrics about the servers.
type RepoCollector struct {
client *dockerhub.Client
logger log.Logger
logger *slog.Logger
failures *prometheus.CounterVec
duration *prometheus.HistogramVec
config config.Target
Expand All @@ -32,15 +31,15 @@ type RepoCollector struct {
}

// NewRepoCollector returns a new RepoCollector.
func NewRepoCollector(logger log.Logger, client *dockerhub.Client, failures *prometheus.CounterVec, duration *prometheus.HistogramVec, cfg config.Target) *RepoCollector {
func NewRepoCollector(logger *slog.Logger, client *dockerhub.Client, failures *prometheus.CounterVec, duration *prometheus.HistogramVec, cfg config.Target) *RepoCollector {
if failures != nil {
failures.WithLabelValues("repo").Add(0)
}

labels := []string{"owner", "name"}
return &RepoCollector{
client: client,
logger: log.With(logger, "collector", "repo"),
logger: logger.With("collector", "repo"),
failures: failures,
duration: duration,
config: cfg,
Expand Down Expand Up @@ -134,8 +133,7 @@ func (c *RepoCollector) Collect(ch chan<- prometheus.Metric) {
result, err := c.client.ByOrg(ctx, org)

if err != nil {
level.Error(c.logger).Log(
"msg", "Failed to fetch repos",
c.logger.Error("Failed to fetch repos",
"type", "org",
"name", org,
"err", err,
Expand All @@ -157,8 +155,7 @@ func (c *RepoCollector) Collect(ch chan<- prometheus.Metric) {
result, err := c.client.ByUser(ctx, user)

if err != nil {
level.Error(c.logger).Log(
"msg", "Failed to fetch repos",
c.logger.Error("Failed to fetch repos",
"type", "user",
"name", user,
"err", err,
Expand All @@ -180,8 +177,7 @@ func (c *RepoCollector) Collect(ch chan<- prometheus.Metric) {
result, err := c.client.ByName(ctx, repo)

if err != nil {
level.Error(c.logger).Log(
"msg", "Failed to fetch repos",
c.logger.Error("Failed to fetch repos",
"type", "repo",
"name", repo,
"err", err,
Expand All @@ -201,8 +197,7 @@ func (c *RepoCollector) Collect(ch chan<- prometheus.Metric) {

c.duration.WithLabelValues("repo").Observe(time.Since(now).Seconds())

level.Debug(c.logger).Log(
"msg", "Fetched repos",
c.logger.Debug("Fetched repos",
"count", len(repos),
"duration", time.Since(now),
)
Expand Down
9 changes: 3 additions & 6 deletions pkg/middleware/recoverer.go
Original file line number Diff line number Diff line change
@@ -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()),
)

Expand Down

0 comments on commit eee0476

Please sign in to comment.