From 3f58328db52991fea84fb71d7e0bd7c379aa7bb5 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 9 Sep 2024 18:53:27 +0000 Subject: [PATCH 1/2] minor(deps): update module github.com/prometheus/exporter-toolkit to v0.13.0 --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 12a3a1e..36bf894 100644 --- a/go.mod +++ b/go.mod @@ -8,7 +8,7 @@ require ( github.com/joho/godotenv v1.5.1 github.com/oklog/run v1.1.0 github.com/prometheus/client_golang v1.20.3 - github.com/prometheus/exporter-toolkit v0.12.0 + github.com/prometheus/exporter-toolkit v0.13.0 github.com/stretchr/testify v1.9.0 github.com/urfave/cli/v2 v2.27.4 ) diff --git a/go.sum b/go.sum index 7482e13..3380fce 100644 --- a/go.sum +++ b/go.sum @@ -47,8 +47,8 @@ github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY= github.com/prometheus/common v0.58.0 h1:N+N8vY4/23r6iYfD3UQZUoJPnUYAo7v6LG5XZxjZTXo= github.com/prometheus/common v0.58.0/go.mod h1:GpWM7dewqmVYcd7SmRaiWVe9SSqjf0UrwnYnpEZNuT0= -github.com/prometheus/exporter-toolkit v0.12.0 h1:DkE5RcEZR3lQA2QD5JLVQIf41dFKNsVMXFhgqcif7fo= -github.com/prometheus/exporter-toolkit v0.12.0/go.mod h1:fQH0KtTn0yrrS0S82kqppRjDDiwMfIQUwT+RBRRhwUc= +github.com/prometheus/exporter-toolkit v0.13.0 h1:lmA0Q+8IaXgmFRKw09RldZmZdnvu9wwcDLIXGmTPw1c= +github.com/prometheus/exporter-toolkit v0.13.0/go.mod h1:2uop99EZl80KdXhv/MxVI2181fMcwlsumFOqBecGkG0= github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc= github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk= github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= From f14ef888ff3db3316440e18dcc6be147efe7a766 Mon Sep 17 00:00:00 2001 From: Thomas Boerger Date: Sat, 14 Sep 2024 13:45:58 +0200 Subject: [PATCH 2/2] feat: replace go-kit logger by slog --- Makefile | 2 +- changelog/unreleased/logging-library.md | 7 +++++ pkg/action/metrics.go | 9 ++---- pkg/action/server.go | 34 ++++++++------------- pkg/command/command.go | 6 +--- pkg/command/health.go | 11 +++---- pkg/command/setup.go | 40 ++++++++++++------------- pkg/exporter/job.go | 15 ++++------ pkg/middleware/recoverer.go | 9 ++---- 9 files changed, 58 insertions(+), 75 deletions(-) create mode 100644 changelog/unreleased/logging-library.md diff --git a/Makefile b/Makefile index 04217fc..53b6ce4 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..96eb5e4 --- /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/jenkins_exporter/issues/104 diff --git a/pkg/action/metrics.go b/pkg/action/metrics.go index 18d0f7c..1375b39 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/jenkins_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 60dcf00..19d8c08 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 Jenkins Exporter", +func Server(cfg *config.Config, logger *slog.Logger) error { + logger.Info("Launching Jenkins 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, ) @@ -60,8 +56,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, ) @@ -79,9 +74,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( @@ -98,16 +92,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, ) }) @@ -130,7 +122,7 @@ func Server(cfg *config.Config, logger log.Logger) error { return gr.Run() } -func handler(cfg *config.Config, logger log.Logger, client *jenkins.Client) *chi.Mux { +func handler(cfg *config.Config, logger *slog.Logger, client *jenkins.Client) *chi.Mux { mux := chi.NewRouter() mux.Use(middleware.Recoverer(logger)) mux.Use(middleware.RealIP) @@ -142,9 +134,7 @@ func handler(cfg *config.Config, logger log.Logger, client *jenkins.Client) *chi } if cfg.Collector.Jobs { - level.Debug(logger).Log( - "msg", "Jobs collector registered", - ) + logger.Debug("Jobs collector registered") registry.MustRegister(exporter.NewJobCollector( logger, diff --git a/pkg/command/command.go b/pkg/command/command.go index c25f3f8..c910fca 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/jenkins_exporter/pkg/action" "github.com/promhippie/jenkins_exporter/pkg/config" "github.com/promhippie/jenkins_exporter/pkg/version" @@ -34,10 +33,7 @@ func Run() error { logger := setupLogger(cfg) if cfg.Target.Address == "" { - level.Error(logger).Log( - "msg", "Missing required jenkins.url", - ) - + logger.Error("Missing required jenkins.url") return fmt.Errorf("missing required jenkins.url") } diff --git a/pkg/command/health.go b/pkg/command/health.go index 8b72526..b8792ac 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/jenkins_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 a64ba1d..cf2479d 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/jenkins_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/job.go b/pkg/exporter/job.go index 3a02fe3..ab3b554 100644 --- a/pkg/exporter/job.go +++ b/pkg/exporter/job.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/jenkins_exporter/pkg/config" "github.com/promhippie/jenkins_exporter/pkg/internal/jenkins" @@ -14,7 +13,7 @@ import ( // JobCollector collects metrics about the servers. type JobCollector struct { client *jenkins.Client - logger log.Logger + logger *slog.Logger failures *prometheus.CounterVec duration *prometheus.HistogramVec config config.Target @@ -33,7 +32,7 @@ type JobCollector struct { } // NewJobCollector returns a new JobCollector. -func NewJobCollector(logger log.Logger, client *jenkins.Client, failures *prometheus.CounterVec, duration *prometheus.HistogramVec, cfg config.Target) *JobCollector { +func NewJobCollector(logger *slog.Logger, client *jenkins.Client, failures *prometheus.CounterVec, duration *prometheus.HistogramVec, cfg config.Target) *JobCollector { if failures != nil { failures.WithLabelValues("job").Add(0) } @@ -41,7 +40,7 @@ func NewJobCollector(logger log.Logger, client *jenkins.Client, failures *promet labels := []string{"name", "path", "class"} return &JobCollector{ client: client, - logger: log.With(logger, "collector", "job"), + logger: logger.With("collector", "job"), failures: failures, duration: duration, config: cfg, @@ -157,8 +156,7 @@ func (c *JobCollector) Collect(ch chan<- prometheus.Metric) { c.duration.WithLabelValues("job").Observe(time.Since(now).Seconds()) if err != nil { - level.Error(c.logger).Log( - "msg", "Failed to fetch jobs", + c.logger.Error("Failed to fetch jobs", "err", err, ) @@ -166,8 +164,7 @@ func (c *JobCollector) Collect(ch chan<- prometheus.Metric) { return } - level.Debug(c.logger).Log( - "msg", "Fetched jobs", + c.logger.Debug("Fetched jobs", "count", len(jobs), ) 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()), )