Skip to content

Commit

Permalink
Move from github.com/go-kit/log to log/slog
Browse files Browse the repository at this point in the history
Signed-off-by: Mario Trangoni <[email protected]>
  • Loading branch information
mario-trangoni-flw authored and mjtrangoni committed Nov 25, 2024
1 parent f127124 commit 4d9d6fd
Show file tree
Hide file tree
Showing 9 changed files with 90 additions and 70 deletions.
3 changes: 1 addition & 2 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,7 @@ linters-settings:
- $gostd
- github.com/mjtrangoni/flexlm_exporter
- github.com/prometheus/client_golang
- github.com/go-kit/log
- github.com/prometheus/common/promlog
- github.com/prometheus/common/promslog
- github.com/prometheus/common/version
- github.com/prometheus/exporter-toolkit/web
- github.com/alecthomas/kingpin/v2
Expand Down
35 changes: 23 additions & 12 deletions collector/collector.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@
package collector

import (
"errors"
"fmt"
"log/slog"
"strconv"
"sync"
"time"

kingpin "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus"
)

Expand Down Expand Up @@ -57,14 +57,14 @@ const (
)

var (
factories = make(map[string]func(logger log.Logger) (Collector, error))
factories = make(map[string]func(logger *slog.Logger) (Collector, error))
initiatedCollectorsMtx = sync.Mutex{}
initiatedCollectors = make(map[string]Collector)
collectorState = make(map[string]*bool)
forcedCollectors = map[string]bool{} // collectors which have been explicitly enabled or disabled
)

func registerCollector(collector string, isDefaultEnabled bool, factory func(logger log.Logger) (Collector, error)) {
func registerCollector(collector string, isDefaultEnabled bool, factory func(logger *slog.Logger) (Collector, error)) {
var helpDefaultState string
if isDefaultEnabled {
helpDefaultState = "enabled"
Expand All @@ -85,7 +85,7 @@ func registerCollector(collector string, isDefaultEnabled bool, factory func(log
// FlexlmCollector implements the prometheus.Collector interface.
type FlexlmCollector struct {
Collectors map[string]Collector
logger log.Logger
logger *slog.Logger
}

// collectorFlagAction generates a new action function for the given collector
Expand All @@ -102,10 +102,10 @@ func collectorFlagAction(collector string) func(ctx *kingpin.ParseContext) error
}
}

//revive:enable:unused-parameter

// NewFlexlmCollector creates a new FlexlmCollector.
func NewFlexlmCollector(logger log.Logger, filters ...string) (*FlexlmCollector, error) {
//
//revive:enable:unused-parameter
func NewFlexlmCollector(logger *slog.Logger, filters ...string) (*FlexlmCollector, error) {
f := make(map[string]bool)

for _, filter := range filters {
Expand All @@ -132,7 +132,7 @@ func NewFlexlmCollector(logger log.Logger, filters ...string) (*FlexlmCollector,
if collector, ok := initiatedCollectors[key]; ok {
collectors[key] = collector
} else {
collector, err := factories[key](log.With(logger, "collector", key))
collector, err := factories[key](logger.With("collector", key))
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -168,19 +168,23 @@ func (n FlexlmCollector) Collect(ch chan<- prometheus.Metric) {
wg.Wait()
}

func execute(name string, c Collector, ch chan<- prometheus.Metric, logger log.Logger) {
func execute(name string, c Collector, ch chan<- prometheus.Metric, logger *slog.Logger) {
var success float64

begin := time.Now()
err := c.Update(ch)
duration := time.Since(begin)

if err != nil {
level.Error(logger).Log(name, "collector failed after:", duration.Seconds(), ":", err)
if IsNoDataError(err) {
logger.Debug("collector returned no data", "name", name, "duration_seconds", duration.Seconds(), "err", err)
} else {
logger.Error("collector failed", "name", name, "duration_seconds", duration.Seconds(), "err", err)
}

success = 0
} else {
level.Debug(logger).Log("OK:", name, "collector succeeded after:", duration.Seconds())
logger.Debug("collector succeeded", "name", name, "duration_seconds", duration.Seconds())

success = 1
}
Expand All @@ -193,3 +197,10 @@ type Collector interface {
// Get new metrics and expose them via prometheus registry.
Update(ch chan<- prometheus.Metric) error
}

// ErrNoData indicates the collector found no data to collect, but had no other error.
var ErrNoData = errors.New("collector returned no data")

func IsNoDataError(err error) bool {
return err == ErrNoData
}
29 changes: 14 additions & 15 deletions collector/lmstat.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"bytes"
"encoding/csv"
"fmt"
"log/slog"
"os"
"os/exec"
"regexp"
Expand All @@ -25,8 +26,6 @@ import (
"sync"
"time"

"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/mjtrangoni/flexlm_exporter/config"
"github.com/prometheus/client_golang/prometheus"
)
Expand All @@ -41,7 +40,7 @@ type lmstatCollector struct {
lmstatFeatureReservGroups *prometheus.Desc
lmstatFeatureReservHost *prometheus.Desc
lmstatFeatureIssued *prometheus.Desc
logger log.Logger
logger *slog.Logger
}

// LicenseConfig is going to be read once in main, and then used here.
Expand All @@ -56,7 +55,7 @@ func init() {
}

// NewLmstatCollector returns a new Collector exposing lmstat license stats.
func NewLmstatCollector(logger log.Logger) (Collector, error) {
func NewLmstatCollector(logger *slog.Logger) (Collector, error) {
return &lmstatCollector{
lmstatInfo: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "lmstat", "info"),
Expand Down Expand Up @@ -138,10 +137,10 @@ func contains(slice []string, item string) bool {
}

// execute lmutil utility.
func lmutilOutput(logger log.Logger, args ...string) ([]byte, error) {
func lmutilOutput(logger *slog.Logger, args ...string) ([]byte, error) {
_, err := os.Stat(*lmutilPath)
if os.IsNotExist(err) {
level.Error(logger).Log("err", *lmutilPath, "missing")
logger.Error("err", *lmutilPath, "missing")
os.Exit(1)
}

Expand Down Expand Up @@ -273,7 +272,7 @@ func parseLmstatLicenseInfoVendor(outStr [][]string) map[string]*vendor {
return vendors
}

func parseLmstatLicenseInfoFeature(outStr [][]string, logger log.Logger) (map[string]*feature,
func parseLmstatLicenseInfoFeature(outStr [][]string, logger *slog.Logger) (map[string]*feature,
map[string]map[string][]*featureUserUsed, map[string]map[string]float64, map[string]map[string]float64) {
features := make(map[string]*feature)
licUsersByFeature := make(map[string]map[string][]*featureUserUsed)
Expand All @@ -289,14 +288,14 @@ func parseLmstatLicenseInfoFeature(outStr [][]string, logger log.Logger) (map[st

issued, err := strconv.Atoi(matches[2])
if err != nil {
level.Error(logger).Log("could not convert", matches[2], "to integer:", err)
logger.Error("err", "could not convert", matches[2], "to integer:", err)
}

featureName = matches[1]

used, err := strconv.Atoi(matches[3])
if err != nil {
level.Error(logger).Log("could not convert", matches[3], "to integer:", err)
logger.Error("err", "could not convert", matches[3], "to integer:", err)
}

features[featureName] = &feature{
Expand All @@ -312,7 +311,7 @@ func parseLmstatLicenseInfoFeature(outStr [][]string, logger log.Logger) (map[st
username := matches["user"]

if strings.TrimSpace(username) == "" {
level.Debug(logger).Log("username couldn't be found for '", lineJoined,
logger.Debug("username couldn't be found for '", lineJoined,
"', using lmutilLicenseFeatureUsageUser2Regex.")

matches = reSubMatchMap(lmutilLicenseFeatureUsageUser2Regex, lineJoined)
Expand All @@ -337,7 +336,7 @@ func parseLmstatLicenseInfoFeature(outStr [][]string, logger log.Logger) (map[st
if matches["licenses"] != "" {
licUsed, err := strconv.Atoi(matches["licenses"])
if err != nil {
level.Error(logger).Log("could not convert", matches["licenses"], "to integer:", err)
logger.Error("err", "could not convert", matches["licenses"], "to integer:", err)
}

for i := range licUsersByFeature[featureName][username] {
Expand All @@ -361,7 +360,7 @@ func parseLmstatLicenseInfoFeature(outStr [][]string, logger log.Logger) (map[st

groupReserv, err := strconv.Atoi(matches[2])
if err != nil {
level.Error(logger).Log("could not convert", matches[1], "to integer:", err)
logger.Error("err", "could not convert", matches[1], "to integer:", err)
}

reservGroupByFeature[featureName][matches[4]] = float64(groupReserv)
Expand All @@ -374,7 +373,7 @@ func parseLmstatLicenseInfoFeature(outStr [][]string, logger log.Logger) (map[st
hostReserv, err := strconv.Atoi(matches[2])

if err != nil {
level.Error(logger).Log("could not convert", matches[1], "to integer:", err)
logger.Error("err", "could not convert", matches[1], "to integer:", err)
}

reservHostByFeature[featureName][matches[4]] = float64(hostReserv)
Expand Down Expand Up @@ -555,7 +554,7 @@ func reSubMatchMap(r *regexp.Regexp, str string) map[string]string {
return subMatchMap
}

func convertLmstatTimeToUnixTime(lmtime string, logger log.Logger) time.Time {
func convertLmstatTimeToUnixTime(lmtime string, logger *slog.Logger) time.Time {
matches := reSubMatchMap(lmutilTimeRegex, lmtime)

// current time and offset (lmstat outputs the time for the current time zone of the server where it is executed)
Expand All @@ -574,7 +573,7 @@ func convertLmstatTimeToUnixTime(lmtime string, logger log.Logger) time.Time {
ltime = ltime.Add(-time.Duration(offset) * time.Second)

if err != nil {
level.Error(logger).Log("could not convert", ltime, "to unix time:", err)
logger.Error("err", "could not convert", ltime, "to unix time:", err)

// fallback, just return the current time in case of errors
return ctime
Expand Down
13 changes: 6 additions & 7 deletions collector/lmstat_feature_exp.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,14 @@ package collector

import (
"fmt"
"log/slog"
"math"
"sort"
"strconv"
"strings"
"sync"
"time"

"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/mjtrangoni/flexlm_exporter/config"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/text/cases"
Expand All @@ -39,7 +38,7 @@ const (
type lmstatFeatureExpCollector struct {
lmstatFeatureExp *prometheus.Desc
lmstatFeatureAggrExp *prometheus.Desc
logger log.Logger
logger *slog.Logger
}

func init() {
Expand All @@ -49,7 +48,7 @@ func init() {

// NewLmstatFeatureExpCollector returns a new Collector exposing lmstat license
// feature expiration date.
func NewLmstatFeatureExpCollector(logger log.Logger) (Collector, error) {
func NewLmstatFeatureExpCollector(logger *slog.Logger) (Collector, error) {
return &lmstatFeatureExpCollector{
lmstatFeatureExp: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "feature",
Expand Down Expand Up @@ -80,7 +79,7 @@ func (c *lmstatFeatureExpCollector) Update(ch chan<- prometheus.Metric) error {
return nil
}

func parseLmstatLicenseFeatureExpDate(outStr [][]string, logger log.Logger) map[int]*featureExp {
func parseLmstatLicenseFeatureExpDate(outStr [][]string, logger *slog.Logger) map[int]*featureExp {
var (
expires float64
index int
Expand All @@ -106,7 +105,7 @@ func parseLmstatLicenseFeatureExpDate(outStr [][]string, logger log.Logger) map[
vendorIndex = 4
}

level.Debug(logger).Log(matches)
logger.Debug("debug", "matches", matches)
// Parse date, month has to be capitalized.
slice := strings.Split(matches[expIndex], "-")
if len(slice) > lenghtOne {
Expand All @@ -126,7 +125,7 @@ func parseLmstatLicenseFeatureExpDate(outStr [][]string, logger log.Logger) map[
fmt.Sprintf("%s-%s-%s", day,
cases.Title(language.English).String(month), year))
if err != nil {
level.Error(logger).Log("could not convert to date:", err)
logger.Error("err", "could not convert to date:", err)
}

if expireDate.Unix() <= 0 {
Expand Down
8 changes: 5 additions & 3 deletions collector/lmstat_feature_exp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import (
"os"
"testing"

"github.com/go-kit/log"
"github.com/prometheus/common/promslog"
)

const (
Expand All @@ -43,7 +43,8 @@ func TestParseLmstatLicenseFeatureExpDate1(t *testing.T) {
t.Fatal(err)
}

featuresExp := parseLmstatLicenseFeatureExpDate(dataStr, log.NewNopLogger())
logger := promslog.New(&promslog.Config{})
featuresExp := parseLmstatLicenseFeatureExpDate(dataStr, logger)
found := false

for index, feature := range featuresExp {
Expand Down Expand Up @@ -119,7 +120,8 @@ func TestParseLmstatLicenseFeatureExpDate2(t *testing.T) {
t.Fatal(err)
}

featuresExp := parseLmstatLicenseFeatureExpDate(dataStr, log.NewNopLogger())
logger := promslog.New(&promslog.Config{})
featuresExp := parseLmstatLicenseFeatureExpDate(dataStr, logger)
found := false

for index, feature := range featuresExp {
Expand Down
10 changes: 7 additions & 3 deletions collector/lmstat_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import (
"testing"
"time"

"github.com/go-kit/log"
"github.com/prometheus/common/promslog"
)

const (
Expand Down Expand Up @@ -210,7 +210,9 @@ func TestParseLmstatLicenseInfoFeature(t *testing.T) {
t.Fatal(err)
}

features, licUsersByFeature, reservGroupByFeature, reservHostByFeature := parseLmstatLicenseInfoFeature(dataStr, log.NewNopLogger())
logger := promslog.New(&promslog.Config{})
features, licUsersByFeature, reservGroupByFeature, reservHostByFeature := parseLmstatLicenseInfoFeature(dataStr, logger)

for name, info := range features {
if name == "feature11" {
if info.issued != 16384 || info.used != 80 {
Expand Down Expand Up @@ -358,7 +360,9 @@ func TestParseLmstatLicenseInfoUserSince(t *testing.T) {
t.Fatal(err)
}

_, licUsersByFeature, _, _ := parseLmstatLicenseInfoFeature(dataStr, log.NewNopLogger())
logger := promslog.New(&promslog.Config{})
_, licUsersByFeature, _, _ := parseLmstatLicenseInfoFeature(dataStr,
logger)

// the year does not matter in this case, since lmstat omits the year information
ctime := time.Now()
Expand Down
11 changes: 5 additions & 6 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,10 @@ package config

import (
"fmt"
"log/slog"
"os"
"path/filepath"

"github.com/go-kit/log"
"github.com/go-kit/log/level"
"gopkg.in/yaml.v3"
)

Expand All @@ -44,9 +43,9 @@ type Configuration struct {
}

// Load parses the YAML file.
func Load(filename string, logger log.Logger) (Configuration, error) {
level.Info(logger).Log("msg", "Loading license config file:")
level.Info(logger).Log(" - ", filename)
func Load(filename string, logger *slog.Logger) (Configuration, error) {
logger.Info("Loading license config file:")
logger.Info(filename)

bytes, err := os.ReadFile(filepath.Clean(filename))
if err != nil {
Expand All @@ -58,7 +57,7 @@ func Load(filename string, logger log.Logger) (Configuration, error) {
err = yaml.Unmarshal(bytes, &c)

if err != nil {
level.Error(logger).Log("Couldn't load config file: ", err)
logger.Error(fmt.Sprintf("Couldn't load config file: %v", err))
return c, err
}

Expand Down
Loading

0 comments on commit 4d9d6fd

Please sign in to comment.