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 c293ca3 commit ca21718
Show file tree
Hide file tree
Showing 10 changed files with 78 additions and 127 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/prometheus-vcd-sd/issues/292
39 changes: 12 additions & 27 deletions pkg/action/discoverer.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@ package action

import (
"context"
"errors"
"fmt"
"log/slog"
"strconv"
"strings"
"time"

"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/discovery/targetgroup"
"github.com/promhippie/prometheus-vcd-sd/pkg/client"
Expand All @@ -34,15 +32,12 @@ var (
"storageProfile": providerPrefix + "storage_profile",
"vdc": providerPrefix + "vdc",
}

// ErrClientEndpoint defines an error if the client auth fails.
ErrClientEndpoint = errors.New("failed to parse api url")
)

// Discoverer implements the Prometheus discoverer interface.
type Discoverer struct {
configs map[string]*client.Client
logger log.Logger
logger *slog.Logger
refresh int
separator string
lasts map[string]struct{}
Expand Down Expand Up @@ -74,8 +69,7 @@ func (d *Discoverer) getTargets(_ context.Context) ([]*targetgroup.Group, error)

for project, config := range d.configs {
if err := config.Authenticate(); err != nil {
level.Warn(d.logger).Log(
"msg", "Failed to authenticate",
d.logger.Error("Failed to authenticate",
"project", project,
"err", err,
)
Expand All @@ -91,8 +85,7 @@ func (d *Discoverer) getTargets(_ context.Context) ([]*targetgroup.Group, error)
requestDuration.WithLabelValues(project, "org").Observe(time.Since(nowOrg).Seconds())

if err != nil {
level.Warn(d.logger).Log(
"msg", "Failed to fetch org",
d.logger.Error("Failed to fetch org",
"project", project,
"err", err,
)
Expand All @@ -106,8 +99,7 @@ func (d *Discoverer) getTargets(_ context.Context) ([]*targetgroup.Group, error)
requestDuration.WithLabelValues(project, "vdc").Observe(time.Since(nowVdc).Seconds())

if err != nil {
level.Warn(d.logger).Log(
"msg", "Failed to fetch vdc",
d.logger.Error("Failed to fetch vdc",
"project", project,
"err", err,
)
Expand All @@ -132,8 +124,7 @@ func (d *Discoverer) getTargets(_ context.Context) ([]*targetgroup.Group, error)
requestDuration.WithLabelValues(project, "vapp").Observe(time.Since(nowVapp).Seconds())

if err != nil {
level.Warn(d.logger).Log(
"msg", "Failed to fetch servers",
d.logger.Error("Failed to fetch servers",
"project", project,
"vapp", vappName,
"err", err,
Expand All @@ -144,8 +135,7 @@ func (d *Discoverer) getTargets(_ context.Context) ([]*targetgroup.Group, error)
}

if vapp.VApp.Children == nil {
level.Debug(d.logger).Log(
"msg", "No servers defined",
d.logger.Debug("No servers defined",
"project", project,
"vapp", vappName,
)
Expand All @@ -155,8 +145,7 @@ func (d *Discoverer) getTargets(_ context.Context) ([]*targetgroup.Group, error)

servers := vapp.VApp.Children.VM

level.Debug(d.logger).Log(
"msg", "Requested servers",
d.logger.Debug("Requested servers",
"project", project,
"vapp", vappName,
"count", len(servers),
Expand All @@ -172,8 +161,7 @@ func (d *Discoverer) getTargets(_ context.Context) ([]*targetgroup.Group, error)
requestDuration.WithLabelValues(project, "vm").Observe(time.Since(nowMachine).Seconds())

if err != nil {
level.Warn(d.logger).Log(
"msg", "Failed to fetch vm",
d.logger.Error("Failed to fetch vm",
"project", project,
"vapp", vappName,
"server", server.Name,
Expand All @@ -190,8 +178,7 @@ func (d *Discoverer) getTargets(_ context.Context) ([]*targetgroup.Group, error)
requestDuration.WithLabelValues(project, "metadata").Observe(time.Since(nowMeta).Seconds())

if err != nil {
level.Warn(d.logger).Log(
"msg", "Failed to fetch metadata",
d.logger.Error("Failed to fetch metadata",
"project", project,
"vapp", vappName,
"server", server.Name,
Expand Down Expand Up @@ -244,8 +231,7 @@ func (d *Discoverer) getTargets(_ context.Context) ([]*targetgroup.Group, error)
target.Labels[model.LabelName(Labels["metadataPrefix"]+normalized)] = model.LabelValue(entry.TypedValue.Value)
}

level.Debug(d.logger).Log(
"msg", "Server added",
d.logger.Debug("Server added",
"project", project,
"vapp", vappName,
"server", vm.VM.Name,
Expand All @@ -262,8 +248,7 @@ func (d *Discoverer) getTargets(_ context.Context) ([]*targetgroup.Group, error)

for k := range d.lasts {
if _, ok := current[k]; !ok {
level.Debug(d.logger).Log(
"msg", "Server deleted",
d.logger.Debug("Server deleted",
"source", k,
)

Expand Down
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/prometheus-vcd-sd/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...))
}
35 changes: 13 additions & 22 deletions pkg/action/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,14 @@ import (
"context"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"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 @@ -24,9 +23,8 @@ import (
)

// Server handles the server sub-command.
func Server(cfg *config.Config, logger log.Logger) error {
level.Info(logger).Log(
"msg", "Launching Prometheus vCloud Director SD",
func Server(cfg *config.Config, logger *slog.Logger) error {
logger.Info("Launching Prometheus vCloud Director SD",
"version", version.String,
"revision", version.Revision,
"date", version.Date,
Expand All @@ -44,8 +42,7 @@ func Server(cfg *config.Config, logger log.Logger) error {
username, err := config.Value(credential.Username)

if err != nil {
level.Error(logger).Log(
"msg", "Failed to read username secret",
logger.Error("Failed to read username secret",
"project", credential.Project,
"err", err,
)
Expand All @@ -56,8 +53,7 @@ func Server(cfg *config.Config, logger log.Logger) error {
password, err := config.Value(credential.Password)

if err != nil {
level.Error(logger).Log(
"msg", "Failed to read password secret",
logger.Error("Failed to read password secret",
"project", credential.Project,
"err", err,
)
Expand All @@ -68,12 +64,11 @@ func Server(cfg *config.Config, logger log.Logger) error {
parsed, err := url.ParseRequestURI(credential.URL)

if err != nil {
level.Error(logger).Log(
"msg", ErrClientEndpoint,
logger.Error("Failed to parse api url",
"project", credential.Project,
)

return ErrClientEndpoint
return fmt.Errorf("failed to parse api url")
}

configs[credential.Project] = client.New(
Expand Down Expand Up @@ -107,9 +102,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 @@ -126,16 +120,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 @@ -158,7 +150,7 @@ func Server(cfg *config.Config, logger log.Logger) error {
return gr.Run()
}

func handler(cfg *config.Config, logger log.Logger) *chi.Mux {
func handler(cfg *config.Config, logger *slog.Logger) *chi.Mux {
mux := chi.NewRouter()
mux.Use(middleware.Recoverer(logger))
mux.Use(middleware.RealIP)
Expand Down Expand Up @@ -198,8 +190,7 @@ func handler(cfg *config.Config, logger log.Logger) *chi.Mux {
content, err := os.ReadFile(cfg.Target.File)

if err != nil {
level.Info(logger).Log(
"msg", "Failed to read service discovery data",
logger.Error("Failed to read service discovery data",
"err", err,
)

Expand Down
11 changes: 5 additions & 6 deletions pkg/adapter/adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,11 @@ import (
"context"
"encoding/json"
"fmt"
"log/slog"
"os"
"path/filepath"
"reflect"

"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/prometheus/discovery"
"github.com/prometheus/prometheus/discovery/targetgroup"
)
Expand All @@ -43,7 +42,7 @@ type Adapter struct {
manager *discovery.Manager
output string
name string
logger log.Logger
logger *slog.Logger
}

func mapToArray(m map[string]*customSD) []customSD {
Expand Down Expand Up @@ -84,7 +83,7 @@ func (a *Adapter) generateTargetGroups(allTargetGroups map[string][]*targetgroup
a.groups = tempGroups
err := a.writeOutput()
if err != nil {
level.Error(log.With(a.logger, "component", "sd-adapter")).Log("err", err)
a.logger.With("component", "sd-adapter").Error("", "err", err)
}
}

Expand Down Expand Up @@ -138,12 +137,12 @@ func (a *Adapter) Run() {
}

// NewAdapter creates a new instance of Adapter.
func NewAdapter(ctx context.Context, file string, name string, d discovery.Discoverer, logger log.Logger) *Adapter {
func NewAdapter(ctx context.Context, file string, name string, d discovery.Discoverer, logger *slog.Logger) *Adapter {
return &Adapter{
ctx: ctx,
disc: d,
groups: make(map[string]*customSD),
manager: discovery.NewManager(ctx, logger),
manager: discovery.NewManager(ctx, nil),
output: file,
name: name,
logger: logger,
Expand Down
14 changes: 7 additions & 7 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/prometheus-vcd-sd/pkg/config"
"github.com/urfave/cli/v2"
)
Expand All @@ -20,8 +19,7 @@ func Health(cfg *config.Config) *cli.Command {

if c.IsSet("vcd.config") {
if err := readConfig(c.String("vcd.config"), cfg); err != nil {
level.Error(logger).Log(
"msg", "Failed to read config",
logger.Error("Failed to read config",
"err", err,
)

Expand All @@ -37,8 +35,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 @@ -48,15 +45,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
Loading

0 comments on commit ca21718

Please sign in to comment.