Update logging
Some checks failed
golangci-lint / lint (push) Has been cancelled

Switch from promlog/go-kit to promslog/slog for logging.
* Update Go build to 1.23.

Signed-off-by: Ben Kochie <superq@gmail.com>
This commit is contained in:
Ben Kochie 2024-08-29 10:58:11 +02:00
parent b9d0932179
commit 79cc810c23
No known key found for this signature in database
GPG key ID: C646B23C9E3245F1
137 changed files with 702 additions and 749 deletions

View file

@ -7,7 +7,7 @@ executors:
# should also be updated. # should also be updated.
golang: golang:
docker: docker:
- image: cimg/go:1.22 - image: cimg/go:1.23
arm: arm:
machine: machine:
image: ubuntu-2204:current image: ubuntu-2204:current

View file

@ -1,7 +1,7 @@
go: go:
# Whenever the Go version is updated here, .circle/config.yml and # Whenever the Go version is updated here, .circle/config.yml and
# .promu.yml should also be updated. # .promu.yml should also be updated.
version: 1.22 version: 1.23
cgo: true cgo: true
repository: repository:
path: github.com/prometheus/node_exporter path: github.com/prometheus/node_exporter

View file

@ -1,7 +1,7 @@
go: go:
# Whenever the Go version is updated here, .circle/config.yml and # Whenever the Go version is updated here, .circle/config.yml and
# .promu-cgo.yml should also be updated. # .promu-cgo.yml should also be updated.
version: 1.22 version: 1.23
repository: repository:
path: github.com/prometheus/node_exporter path: github.com/prometheus/node_exporter
build: build:

View file

@ -19,10 +19,10 @@ package collector
import ( import (
"errors" "errors"
"fmt" "fmt"
"log/slog"
"net" "net"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
"github.com/jsimonetti/rtnetlink" "github.com/jsimonetti/rtnetlink"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/procfs" "github.com/prometheus/procfs"
@ -39,7 +39,7 @@ type arpCollector struct {
fs procfs.FS fs procfs.FS
deviceFilter deviceFilter deviceFilter deviceFilter
entries *prometheus.Desc entries *prometheus.Desc
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -47,7 +47,7 @@ func init() {
} }
// NewARPCollector returns a new Collector exposing ARP stats. // NewARPCollector returns a new Collector exposing ARP stats.
func NewARPCollector(logger log.Logger) (Collector, error) { func NewARPCollector(logger *slog.Logger) (Collector, error) {
fs, err := procfs.NewFS(*procPath) fs, err := procfs.NewFS(*procPath)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to open procfs: %w", err) return nil, fmt.Errorf("failed to open procfs: %w", err)

View file

@ -18,9 +18,9 @@ package collector
import ( import (
"fmt" "fmt"
"log/slog"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/procfs/bcache" "github.com/prometheus/procfs/bcache"
) )
@ -36,12 +36,12 @@ func init() {
// A bcacheCollector is a Collector which gathers metrics from Linux bcache. // A bcacheCollector is a Collector which gathers metrics from Linux bcache.
type bcacheCollector struct { type bcacheCollector struct {
fs bcache.FS fs bcache.FS
logger log.Logger logger *slog.Logger
} }
// NewBcacheCollector returns a newly allocated bcacheCollector. // NewBcacheCollector returns a newly allocated bcacheCollector.
// It exposes a number of Linux bcache statistics. // It exposes a number of Linux bcache statistics.
func NewBcacheCollector(logger log.Logger) (Collector, error) { func NewBcacheCollector(logger *slog.Logger) (Collector, error) {
fs, err := bcache.NewFS(*sysPath) fs, err := bcache.NewFS(*sysPath)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to open sysfs: %w", err) return nil, fmt.Errorf("failed to open sysfs: %w", err)

View file

@ -19,18 +19,17 @@ package collector
import ( import (
"errors" "errors"
"fmt" "fmt"
"log/slog"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
type bondingCollector struct { type bondingCollector struct {
slaves, active typedDesc slaves, active typedDesc
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -39,7 +38,7 @@ func init() {
// NewBondingCollector returns a newly allocated bondingCollector. // NewBondingCollector returns a newly allocated bondingCollector.
// It exposes the number of configured and active slave of linux bonding interfaces. // It exposes the number of configured and active slave of linux bonding interfaces.
func NewBondingCollector(logger log.Logger) (Collector, error) { func NewBondingCollector(logger *slog.Logger) (Collector, error) {
return &bondingCollector{ return &bondingCollector{
slaves: typedDesc{prometheus.NewDesc( slaves: typedDesc{prometheus.NewDesc(
prometheus.BuildFQName(namespace, "bonding", "slaves"), prometheus.BuildFQName(namespace, "bonding", "slaves"),
@ -61,7 +60,7 @@ func (c *bondingCollector) Update(ch chan<- prometheus.Metric) error {
bondingStats, err := readBondingStats(statusfile) bondingStats, err := readBondingStats(statusfile)
if err != nil { if err != nil {
if errors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {
level.Debug(c.logger).Log("msg", "Not collecting bonding, file does not exist", "file", statusfile) c.logger.Debug("Not collecting bonding, file does not exist", "file", statusfile)
return ErrNoData return ErrNoData
} }
return err return err

View file

@ -18,13 +18,13 @@
package collector package collector
import ( import (
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
"log/slog"
) )
type bootTimeCollector struct { type bootTimeCollector struct {
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -32,7 +32,7 @@ func init() {
} }
// newBootTimeCollector returns a new Collector exposing system boot time on BSD systems. // newBootTimeCollector returns a new Collector exposing system boot time on BSD systems.
func newBootTimeCollector(logger log.Logger) (Collector, error) { func newBootTimeCollector(logger *slog.Logger) (Collector, error) {
return &bootTimeCollector{ return &bootTimeCollector{
logger: logger, logger: logger,
}, nil }, nil

View file

@ -17,21 +17,21 @@
package collector package collector
import ( import (
"github.com/go-kit/log"
"github.com/illumos/go-kstat" "github.com/illumos/go-kstat"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"log/slog"
) )
type bootTimeCollector struct { type bootTimeCollector struct {
boottime typedDesc boottime typedDesc
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
registerCollector("boottime", defaultEnabled, newBootTimeCollector) registerCollector("boottime", defaultEnabled, newBootTimeCollector)
} }
func newBootTimeCollector(logger log.Logger) (Collector, error) { func newBootTimeCollector(logger *slog.Logger) (Collector, error) {
return &bootTimeCollector{ return &bootTimeCollector{
boottime: typedDesc{ boottime: typedDesc{
prometheus.NewDesc( prometheus.NewDesc(

View file

@ -18,13 +18,12 @@ package collector
import ( import (
"fmt" "fmt"
"log/slog"
"path" "path"
"strings" "strings"
"syscall" "syscall"
dennwc "github.com/dennwc/btrfs" dennwc "github.com/dennwc/btrfs"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/procfs/btrfs" "github.com/prometheus/procfs/btrfs"
) )
@ -32,7 +31,7 @@ import (
// A btrfsCollector is a Collector which gathers metrics from Btrfs filesystems. // A btrfsCollector is a Collector which gathers metrics from Btrfs filesystems.
type btrfsCollector struct { type btrfsCollector struct {
fs btrfs.FS fs btrfs.FS
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -40,7 +39,7 @@ func init() {
} }
// NewBtrfsCollector returns a new Collector exposing Btrfs statistics. // NewBtrfsCollector returns a new Collector exposing Btrfs statistics.
func NewBtrfsCollector(logger log.Logger) (Collector, error) { func NewBtrfsCollector(logger *slog.Logger) (Collector, error) {
fs, err := btrfs.NewFS(*sysPath) fs, err := btrfs.NewFS(*sysPath)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to open sysfs: %w", err) return nil, fmt.Errorf("failed to open sysfs: %w", err)
@ -62,8 +61,8 @@ func (c *btrfsCollector) Update(ch chan<- prometheus.Metric) error {
ioctlStatsMap, err := c.getIoctlStats() ioctlStatsMap, err := c.getIoctlStats()
if err != nil { if err != nil {
level.Debug(c.logger).Log( c.logger.Debug(
"msg", "Error querying btrfs device stats with ioctl", "Error querying btrfs device stats with ioctl",
"err", err) "err", err)
ioctlStatsMap = make(map[string]*btrfsIoctlFsStats) ioctlStatsMap = make(map[string]*btrfsIoctlFsStats)
} }
@ -129,8 +128,8 @@ func (c *btrfsCollector) getIoctlStats() (map[string]*btrfsIoctlFsStats, error)
if err != nil { if err != nil {
// Failed to open this mount point, maybe we didn't have permission // Failed to open this mount point, maybe we didn't have permission
// maybe we'll find another mount point for this FS later. // maybe we'll find another mount point for this FS later.
level.Debug(c.logger).Log( c.logger.Debug(
"msg", "Error inspecting btrfs mountpoint", "Error inspecting btrfs mountpoint",
"mountPoint", mountPath, "mountPoint", mountPath,
"err", err) "err", err)
continue continue
@ -141,8 +140,8 @@ func (c *btrfsCollector) getIoctlStats() (map[string]*btrfsIoctlFsStats, error)
if err != nil { if err != nil {
// Failed to get the FS info for some reason, // Failed to get the FS info for some reason,
// perhaps it'll work with a different mount point // perhaps it'll work with a different mount point
level.Debug(c.logger).Log( c.logger.Debug(
"msg", "Error querying btrfs filesystem", "Error querying btrfs filesystem",
"mountPoint", mountPath, "mountPoint", mountPath,
"err", err) "err", err)
continue continue
@ -156,8 +155,8 @@ func (c *btrfsCollector) getIoctlStats() (map[string]*btrfsIoctlFsStats, error)
deviceStats, err := c.getIoctlDeviceStats(fs, &fsInfo) deviceStats, err := c.getIoctlDeviceStats(fs, &fsInfo)
if err != nil { if err != nil {
level.Debug(c.logger).Log( c.logger.Debug(
"msg", "Error querying btrfs device stats", "Error querying btrfs device stats",
"mountPoint", mountPath, "mountPoint", mountPath,
"err", err) "err", err)
continue continue

View file

@ -18,10 +18,9 @@ package collector
import ( import (
"fmt" "fmt"
"log/slog"
"strconv" "strconv"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/procfs" "github.com/prometheus/procfs"
) )
@ -33,7 +32,7 @@ const (
type buddyinfoCollector struct { type buddyinfoCollector struct {
fs procfs.FS fs procfs.FS
desc *prometheus.Desc desc *prometheus.Desc
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -41,7 +40,7 @@ func init() {
} }
// NewBuddyinfoCollector returns a new Collector exposing buddyinfo stats. // NewBuddyinfoCollector returns a new Collector exposing buddyinfo stats.
func NewBuddyinfoCollector(logger log.Logger) (Collector, error) { func NewBuddyinfoCollector(logger *slog.Logger) (Collector, error) {
desc := prometheus.NewDesc( desc := prometheus.NewDesc(
prometheus.BuildFQName(namespace, buddyInfoSubsystem, "blocks"), prometheus.BuildFQName(namespace, buddyInfoSubsystem, "blocks"),
"Count of free blocks according to size.", "Count of free blocks according to size.",
@ -62,7 +61,7 @@ func (c *buddyinfoCollector) Update(ch chan<- prometheus.Metric) error {
return fmt.Errorf("couldn't get buddyinfo: %w", err) return fmt.Errorf("couldn't get buddyinfo: %w", err)
} }
level.Debug(c.logger).Log("msg", "Set node_buddy", "buddyInfo", buddyInfo) c.logger.Debug("Set node_buddy", "buddyInfo", buddyInfo)
for _, entry := range buddyInfo { for _, entry := range buddyInfo {
for size, value := range entry.Sizes { for size, value := range entry.Sizes {
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(

View file

@ -18,8 +18,8 @@ package collector
import ( import (
"fmt" "fmt"
"log/slog"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/procfs" "github.com/prometheus/procfs"
) )
@ -30,7 +30,7 @@ type cgroupSummaryCollector struct {
fs procfs.FS fs procfs.FS
cgroups *prometheus.Desc cgroups *prometheus.Desc
enabled *prometheus.Desc enabled *prometheus.Desc
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -38,7 +38,7 @@ func init() {
} }
// NewCgroupSummaryCollector returns a new Collector exposing a summary of cgroups. // NewCgroupSummaryCollector returns a new Collector exposing a summary of cgroups.
func NewCgroupSummaryCollector(logger log.Logger) (Collector, error) { func NewCgroupSummaryCollector(logger *slog.Logger) (Collector, error) {
fs, err := procfs.NewFS(*procPath) fs, err := procfs.NewFS(*procPath)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to open procfs: %w", err) return nil, fmt.Errorf("failed to open procfs: %w", err)

View file

@ -17,12 +17,11 @@ package collector
import ( import (
"errors" "errors"
"fmt" "fmt"
"log/slog"
"sync" "sync"
"time" "time"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -50,14 +49,14 @@ const (
) )
var ( var (
factories = make(map[string]func(logger log.Logger) (Collector, error)) factories = make(map[string]func(logger *slog.Logger) (Collector, error))
initiatedCollectorsMtx = sync.Mutex{} initiatedCollectorsMtx = sync.Mutex{}
initiatedCollectors = make(map[string]Collector) initiatedCollectors = make(map[string]Collector)
collectorState = make(map[string]*bool) collectorState = make(map[string]*bool)
forcedCollectors = map[string]bool{} // collectors which have been explicitly enabled or disabled 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 var helpDefaultState string
if isDefaultEnabled { if isDefaultEnabled {
helpDefaultState = "enabled" helpDefaultState = "enabled"
@ -78,7 +77,7 @@ func registerCollector(collector string, isDefaultEnabled bool, factory func(log
// NodeCollector implements the prometheus.Collector interface. // NodeCollector implements the prometheus.Collector interface.
type NodeCollector struct { type NodeCollector struct {
Collectors map[string]Collector Collectors map[string]Collector
logger log.Logger logger *slog.Logger
} }
// DisableDefaultCollectors sets the collector state to false for all collectors which // DisableDefaultCollectors sets the collector state to false for all collectors which
@ -104,7 +103,7 @@ func collectorFlagAction(collector string) func(ctx *kingpin.ParseContext) error
} }
// NewNodeCollector creates a new NodeCollector. // NewNodeCollector creates a new NodeCollector.
func NewNodeCollector(logger log.Logger, filters ...string) (*NodeCollector, error) { func NewNodeCollector(logger *slog.Logger, filters ...string) (*NodeCollector, error) {
f := make(map[string]bool) f := make(map[string]bool)
for _, filter := range filters { for _, filter := range filters {
enabled, exist := collectorState[filter] enabled, exist := collectorState[filter]
@ -126,7 +125,7 @@ func NewNodeCollector(logger log.Logger, filters ...string) (*NodeCollector, err
if collector, ok := initiatedCollectors[key]; ok { if collector, ok := initiatedCollectors[key]; ok {
collectors[key] = collector collectors[key] = collector
} else { } else {
collector, err := factories[key](log.With(logger, "collector", key)) collector, err := factories[key](logger.With("collector", key))
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -156,7 +155,7 @@ func (n NodeCollector) Collect(ch chan<- prometheus.Metric) {
wg.Wait() 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) {
begin := time.Now() begin := time.Now()
err := c.Update(ch) err := c.Update(ch)
duration := time.Since(begin) duration := time.Since(begin)
@ -164,13 +163,13 @@ func execute(name string, c Collector, ch chan<- prometheus.Metric, logger log.L
if err != nil { if err != nil {
if IsNoDataError(err) { if IsNoDataError(err) {
level.Debug(logger).Log("msg", "collector returned no data", "name", name, "duration_seconds", duration.Seconds(), "err", err) logger.Debug("collector returned no data", "name", name, "duration_seconds", duration.Seconds(), "err", err)
} else { } else {
level.Error(logger).Log("msg", "collector failed", "name", name, "duration_seconds", duration.Seconds(), "err", err) logger.Error("collector failed", "name", name, "duration_seconds", duration.Seconds(), "err", err)
} }
success = 0 success = 0
} else { } else {
level.Debug(logger).Log("msg", "collector succeeded", "name", name, "duration_seconds", duration.Seconds()) logger.Debug("collector succeeded", "name", name, "duration_seconds", duration.Seconds())
success = 1 success = 1
} }
ch <- prometheus.MustNewConstMetric(scrapeDurationDesc, prometheus.GaugeValue, duration.Seconds(), name) ch <- prometheus.MustNewConstMetric(scrapeDurationDesc, prometheus.GaugeValue, duration.Seconds(), name)

View file

@ -19,10 +19,9 @@ package collector
import ( import (
"errors" "errors"
"fmt" "fmt"
"log/slog"
"os" "os"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/procfs" "github.com/prometheus/procfs"
) )
@ -38,7 +37,7 @@ type conntrackCollector struct {
drop *prometheus.Desc drop *prometheus.Desc
earlyDrop *prometheus.Desc earlyDrop *prometheus.Desc
searchRestart *prometheus.Desc searchRestart *prometheus.Desc
logger log.Logger logger *slog.Logger
} }
type conntrackStatistics struct { type conntrackStatistics struct {
@ -57,7 +56,7 @@ func init() {
} }
// NewConntrackCollector returns a new Collector exposing conntrack stats. // NewConntrackCollector returns a new Collector exposing conntrack stats.
func NewConntrackCollector(logger log.Logger) (Collector, error) { func NewConntrackCollector(logger *slog.Logger) (Collector, error) {
return &conntrackCollector{ return &conntrackCollector{
current: prometheus.NewDesc( current: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "nf_conntrack_entries"), prometheus.BuildFQName(namespace, "", "nf_conntrack_entries"),
@ -154,7 +153,7 @@ func (c *conntrackCollector) Update(ch chan<- prometheus.Metric) error {
func (c *conntrackCollector) handleErr(err error) error { func (c *conntrackCollector) handleErr(err error) error {
if errors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {
level.Debug(c.logger).Log("msg", "conntrack probably not loaded") c.logger.Debug("conntrack probably not loaded")
return ErrNoData return ErrNoData
} }
return fmt.Errorf("failed to retrieve conntrack stats: %w", err) return fmt.Errorf("failed to retrieve conntrack stats: %w", err)

View file

@ -23,10 +23,10 @@ import (
"bytes" "bytes"
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"log/slog"
"strconv" "strconv"
"unsafe" "unsafe"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -53,7 +53,7 @@ const ClocksPerSec = float64(C.CLK_TCK)
type statCollector struct { type statCollector struct {
cpu *prometheus.Desc cpu *prometheus.Desc
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -61,7 +61,7 @@ func init() {
} }
// NewCPUCollector returns a new Collector exposing CPU stats. // NewCPUCollector returns a new Collector exposing CPU stats.
func NewCPUCollector(logger log.Logger) (Collector, error) { func NewCPUCollector(logger *slog.Logger) (Collector, error) {
return &statCollector{ return &statCollector{
cpu: nodeCPUSecondsDesc, cpu: nodeCPUSecondsDesc,
logger: logger, logger: logger,

View file

@ -18,10 +18,10 @@ package collector
import ( import (
"errors" "errors"
"log/slog"
"strconv" "strconv"
"unsafe" "unsafe"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -78,7 +78,7 @@ const maxCPUTimesLen = C.MAXCPU * C.CPUSTATES
type statCollector struct { type statCollector struct {
cpu *prometheus.Desc cpu *prometheus.Desc
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -86,7 +86,7 @@ func init() {
} }
// NewStatCollector returns a new Collector exposing CPU stats. // NewStatCollector returns a new Collector exposing CPU stats.
func NewStatCollector(logger log.Logger) (Collector, error) { func NewStatCollector(logger *slog.Logger) (Collector, error) {
return &statCollector{ return &statCollector{
cpu: nodeCPUSecondsDesc, cpu: nodeCPUSecondsDesc,
logger: logger, logger: logger,

View file

@ -18,12 +18,11 @@ package collector
import ( import (
"fmt" "fmt"
"log/slog"
"math" "math"
"strconv" "strconv"
"unsafe" "unsafe"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
@ -85,7 +84,7 @@ func getCPUTimes() ([]cputime, error) {
type statCollector struct { type statCollector struct {
cpu typedDesc cpu typedDesc
temp typedDesc temp typedDesc
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -93,7 +92,7 @@ func init() {
} }
// NewStatCollector returns a new Collector exposing CPU stats. // NewStatCollector returns a new Collector exposing CPU stats.
func NewStatCollector(logger log.Logger) (Collector, error) { func NewStatCollector(logger *slog.Logger) (Collector, error) {
return &statCollector{ return &statCollector{
cpu: typedDesc{nodeCPUSecondsDesc, prometheus.CounterValue}, cpu: typedDesc{nodeCPUSecondsDesc, prometheus.CounterValue},
temp: typedDesc{prometheus.NewDesc( temp: typedDesc{prometheus.NewDesc(
@ -134,11 +133,11 @@ func (c *statCollector) Update(ch chan<- prometheus.Metric) error {
if err != nil { if err != nil {
if err == unix.ENOENT { if err == unix.ENOENT {
// No temperature information for this CPU // No temperature information for this CPU
level.Debug(c.logger).Log("msg", "no temperature information for CPU", "cpu", cpu) c.logger.Debug("no temperature information for CPU", "cpu", cpu)
} else { } else {
// Unexpected error // Unexpected error
ch <- c.temp.mustNewConstMetric(math.NaN(), lcpu) ch <- c.temp.mustNewConstMetric(math.NaN(), lcpu)
level.Error(c.logger).Log("msg", "failed to query CPU temperature for CPU", "cpu", cpu, "err", err) c.logger.Error("failed to query CPU temperature for CPU", "cpu", cpu, "err", err)
} }
continue continue
} }

View file

@ -18,6 +18,7 @@ package collector
import ( import (
"fmt" "fmt"
"log/slog"
"os" "os"
"path/filepath" "path/filepath"
"regexp" "regexp"
@ -26,8 +27,6 @@ import (
"sync" "sync"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/procfs" "github.com/prometheus/procfs"
"github.com/prometheus/procfs/sysfs" "github.com/prometheus/procfs/sysfs"
@ -45,7 +44,7 @@ type cpuCollector struct {
cpuCoreThrottle *prometheus.Desc cpuCoreThrottle *prometheus.Desc
cpuPackageThrottle *prometheus.Desc cpuPackageThrottle *prometheus.Desc
cpuIsolated *prometheus.Desc cpuIsolated *prometheus.Desc
logger log.Logger logger *slog.Logger
cpuStats map[int64]procfs.CPUStat cpuStats map[int64]procfs.CPUStat
cpuStatsMutex sync.Mutex cpuStatsMutex sync.Mutex
isolatedCpus []uint16 isolatedCpus []uint16
@ -70,7 +69,7 @@ func init() {
} }
// NewCPUCollector returns a new Collector exposing kernel/system statistics. // NewCPUCollector returns a new Collector exposing kernel/system statistics.
func NewCPUCollector(logger log.Logger) (Collector, error) { func NewCPUCollector(logger *slog.Logger) (Collector, error) {
fs, err := procfs.NewFS(*procPath) fs, err := procfs.NewFS(*procPath)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to open procfs: %w", err) return nil, fmt.Errorf("failed to open procfs: %w", err)
@ -86,7 +85,7 @@ func NewCPUCollector(logger log.Logger) (Collector, error) {
if !os.IsNotExist(err) { if !os.IsNotExist(err) {
return nil, fmt.Errorf("Unable to get isolated cpus: %w", err) return nil, fmt.Errorf("Unable to get isolated cpus: %w", err)
} }
level.Debug(logger).Log("msg", "Could not open isolated file", "error", err) logger.Debug("Could not open isolated file", "error", err)
} }
c := &cpuCollector{ c := &cpuCollector{
@ -146,7 +145,7 @@ func NewCPUCollector(logger log.Logger) (Collector, error) {
func (c *cpuCollector) compileIncludeFlags(flagsIncludeFlag, bugsIncludeFlag *string) error { func (c *cpuCollector) compileIncludeFlags(flagsIncludeFlag, bugsIncludeFlag *string) error {
if (*flagsIncludeFlag != "" || *bugsIncludeFlag != "") && !*enableCPUInfo { if (*flagsIncludeFlag != "" || *bugsIncludeFlag != "") && !*enableCPUInfo {
*enableCPUInfo = true *enableCPUInfo = true
level.Info(c.logger).Log("msg", "--collector.cpu.info has been set to `true` because you set the following flags, like --collector.cpu.info.flags-include and --collector.cpu.info.bugs-include") c.logger.Info("--collector.cpu.info has been set to `true` because you set the following flags, like --collector.cpu.info.flags-include and --collector.cpu.info.bugs-include")
} }
var err error var err error
@ -205,7 +204,7 @@ func (c *cpuCollector) updateInfo(ch chan<- prometheus.Metric) error {
cpuFreqEnabled, ok := collectorState["cpufreq"] cpuFreqEnabled, ok := collectorState["cpufreq"]
if !ok || cpuFreqEnabled == nil { if !ok || cpuFreqEnabled == nil {
level.Debug(c.logger).Log("msg", "cpufreq key missing or nil value in collectorState map") c.logger.Debug("cpufreq key missing or nil value in collectorState map")
} else if !*cpuFreqEnabled { } else if !*cpuFreqEnabled {
for _, cpu := range info { for _, cpu := range info {
ch <- prometheus.MustNewConstMetric(c.cpuFrequencyHz, ch <- prometheus.MustNewConstMetric(c.cpuFrequencyHz,
@ -269,12 +268,12 @@ func (c *cpuCollector) updateThermalThrottle(ch chan<- prometheus.Metric) error
// topology/physical_package_id // topology/physical_package_id
if physicalPackageID, err = readUintFromFile(filepath.Join(cpu, "topology", "physical_package_id")); err != nil { if physicalPackageID, err = readUintFromFile(filepath.Join(cpu, "topology", "physical_package_id")); err != nil {
level.Debug(c.logger).Log("msg", "CPU is missing physical_package_id", "cpu", cpu) c.logger.Debug("CPU is missing physical_package_id", "cpu", cpu)
continue continue
} }
// topology/core_id // topology/core_id
if coreID, err = readUintFromFile(filepath.Join(cpu, "topology", "core_id")); err != nil { if coreID, err = readUintFromFile(filepath.Join(cpu, "topology", "core_id")); err != nil {
level.Debug(c.logger).Log("msg", "CPU is missing core_id", "cpu", cpu) c.logger.Debug("CPU is missing core_id", "cpu", cpu)
continue continue
} }
@ -292,7 +291,7 @@ func (c *cpuCollector) updateThermalThrottle(ch chan<- prometheus.Metric) error
if coreThrottleCount, err := readUintFromFile(filepath.Join(cpu, "thermal_throttle", "core_throttle_count")); err == nil { if coreThrottleCount, err := readUintFromFile(filepath.Join(cpu, "thermal_throttle", "core_throttle_count")); err == nil {
packageCoreThrottles[physicalPackageID][coreID] = coreThrottleCount packageCoreThrottles[physicalPackageID][coreID] = coreThrottleCount
} else { } else {
level.Debug(c.logger).Log("msg", "CPU is missing core_throttle_count", "cpu", cpu) c.logger.Debug("CPU is missing core_throttle_count", "cpu", cpu)
} }
} }
@ -302,7 +301,7 @@ func (c *cpuCollector) updateThermalThrottle(ch chan<- prometheus.Metric) error
if packageThrottleCount, err := readUintFromFile(filepath.Join(cpu, "thermal_throttle", "package_throttle_count")); err == nil { if packageThrottleCount, err := readUintFromFile(filepath.Join(cpu, "thermal_throttle", "package_throttle_count")); err == nil {
packageThrottles[physicalPackageID] = packageThrottleCount packageThrottles[physicalPackageID] = packageThrottleCount
} else { } else {
level.Debug(c.logger).Log("msg", "CPU is missing package_throttle_count", "cpu", cpu) c.logger.Debug("CPU is missing package_throttle_count", "cpu", cpu)
} }
} }
} }
@ -380,68 +379,68 @@ func (c *cpuCollector) updateCPUStats(newStats map[int64]procfs.CPUStat) {
// If idle jumps backwards by more than X seconds, assume we had a hotplug event and reset the stats for this CPU. // If idle jumps backwards by more than X seconds, assume we had a hotplug event and reset the stats for this CPU.
if (cpuStats.Idle - n.Idle) >= jumpBackSeconds { if (cpuStats.Idle - n.Idle) >= jumpBackSeconds {
level.Debug(c.logger).Log("msg", jumpBackDebugMessage, "cpu", i, "old_value", cpuStats.Idle, "new_value", n.Idle) c.logger.Debug(jumpBackDebugMessage, "cpu", i, "old_value", cpuStats.Idle, "new_value", n.Idle)
cpuStats = procfs.CPUStat{} cpuStats = procfs.CPUStat{}
} }
if n.Idle >= cpuStats.Idle { if n.Idle >= cpuStats.Idle {
cpuStats.Idle = n.Idle cpuStats.Idle = n.Idle
} else { } else {
level.Debug(c.logger).Log("msg", "CPU Idle counter jumped backwards", "cpu", i, "old_value", cpuStats.Idle, "new_value", n.Idle) c.logger.Debug("CPU Idle counter jumped backwards", "cpu", i, "old_value", cpuStats.Idle, "new_value", n.Idle)
} }
if n.User >= cpuStats.User { if n.User >= cpuStats.User {
cpuStats.User = n.User cpuStats.User = n.User
} else { } else {
level.Debug(c.logger).Log("msg", "CPU User counter jumped backwards", "cpu", i, "old_value", cpuStats.User, "new_value", n.User) c.logger.Debug("CPU User counter jumped backwards", "cpu", i, "old_value", cpuStats.User, "new_value", n.User)
} }
if n.Nice >= cpuStats.Nice { if n.Nice >= cpuStats.Nice {
cpuStats.Nice = n.Nice cpuStats.Nice = n.Nice
} else { } else {
level.Debug(c.logger).Log("msg", "CPU Nice counter jumped backwards", "cpu", i, "old_value", cpuStats.Nice, "new_value", n.Nice) c.logger.Debug("CPU Nice counter jumped backwards", "cpu", i, "old_value", cpuStats.Nice, "new_value", n.Nice)
} }
if n.System >= cpuStats.System { if n.System >= cpuStats.System {
cpuStats.System = n.System cpuStats.System = n.System
} else { } else {
level.Debug(c.logger).Log("msg", "CPU System counter jumped backwards", "cpu", i, "old_value", cpuStats.System, "new_value", n.System) c.logger.Debug("CPU System counter jumped backwards", "cpu", i, "old_value", cpuStats.System, "new_value", n.System)
} }
if n.Iowait >= cpuStats.Iowait { if n.Iowait >= cpuStats.Iowait {
cpuStats.Iowait = n.Iowait cpuStats.Iowait = n.Iowait
} else { } else {
level.Debug(c.logger).Log("msg", "CPU Iowait counter jumped backwards", "cpu", i, "old_value", cpuStats.Iowait, "new_value", n.Iowait) c.logger.Debug("CPU Iowait counter jumped backwards", "cpu", i, "old_value", cpuStats.Iowait, "new_value", n.Iowait)
} }
if n.IRQ >= cpuStats.IRQ { if n.IRQ >= cpuStats.IRQ {
cpuStats.IRQ = n.IRQ cpuStats.IRQ = n.IRQ
} else { } else {
level.Debug(c.logger).Log("msg", "CPU IRQ counter jumped backwards", "cpu", i, "old_value", cpuStats.IRQ, "new_value", n.IRQ) c.logger.Debug("CPU IRQ counter jumped backwards", "cpu", i, "old_value", cpuStats.IRQ, "new_value", n.IRQ)
} }
if n.SoftIRQ >= cpuStats.SoftIRQ { if n.SoftIRQ >= cpuStats.SoftIRQ {
cpuStats.SoftIRQ = n.SoftIRQ cpuStats.SoftIRQ = n.SoftIRQ
} else { } else {
level.Debug(c.logger).Log("msg", "CPU SoftIRQ counter jumped backwards", "cpu", i, "old_value", cpuStats.SoftIRQ, "new_value", n.SoftIRQ) c.logger.Debug("CPU SoftIRQ counter jumped backwards", "cpu", i, "old_value", cpuStats.SoftIRQ, "new_value", n.SoftIRQ)
} }
if n.Steal >= cpuStats.Steal { if n.Steal >= cpuStats.Steal {
cpuStats.Steal = n.Steal cpuStats.Steal = n.Steal
} else { } else {
level.Debug(c.logger).Log("msg", "CPU Steal counter jumped backwards", "cpu", i, "old_value", cpuStats.Steal, "new_value", n.Steal) c.logger.Debug("CPU Steal counter jumped backwards", "cpu", i, "old_value", cpuStats.Steal, "new_value", n.Steal)
} }
if n.Guest >= cpuStats.Guest { if n.Guest >= cpuStats.Guest {
cpuStats.Guest = n.Guest cpuStats.Guest = n.Guest
} else { } else {
level.Debug(c.logger).Log("msg", "CPU Guest counter jumped backwards", "cpu", i, "old_value", cpuStats.Guest, "new_value", n.Guest) c.logger.Debug("CPU Guest counter jumped backwards", "cpu", i, "old_value", cpuStats.Guest, "new_value", n.Guest)
} }
if n.GuestNice >= cpuStats.GuestNice { if n.GuestNice >= cpuStats.GuestNice {
cpuStats.GuestNice = n.GuestNice cpuStats.GuestNice = n.GuestNice
} else { } else {
level.Debug(c.logger).Log("msg", "CPU GuestNice counter jumped backwards", "cpu", i, "old_value", cpuStats.GuestNice, "new_value", n.GuestNice) c.logger.Debug("CPU GuestNice counter jumped backwards", "cpu", i, "old_value", cpuStats.GuestNice, "new_value", n.GuestNice)
} }
c.cpuStats[i] = cpuStats c.cpuStats[i] = cpuStats

View file

@ -17,10 +17,11 @@
package collector package collector
import ( import (
"io"
"log/slog"
"reflect" "reflect"
"testing" "testing"
"github.com/go-kit/log"
"github.com/prometheus/procfs" "github.com/prometheus/procfs"
) )
@ -35,7 +36,7 @@ func makeTestCPUCollector(s map[int64]procfs.CPUStat) *cpuCollector {
dup := make(map[int64]procfs.CPUStat, len(s)) dup := make(map[int64]procfs.CPUStat, len(s))
copyStats(dup, s) copyStats(dup, s)
return &cpuCollector{ return &cpuCollector{
logger: log.NewNopLogger(), logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
cpuStats: dup, cpuStats: dup,
} }
} }

View file

@ -18,6 +18,7 @@ package collector
import ( import (
"errors" "errors"
"log/slog"
"math" "math"
"regexp" "regexp"
"sort" "sort"
@ -25,8 +26,6 @@ import (
"strings" "strings"
"unsafe" "unsafe"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
@ -214,7 +213,7 @@ func getCPUTimes() ([]cputime, error) {
type statCollector struct { type statCollector struct {
cpu typedDesc cpu typedDesc
temp typedDesc temp typedDesc
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -222,7 +221,7 @@ func init() {
} }
// NewStatCollector returns a new Collector exposing CPU stats. // NewStatCollector returns a new Collector exposing CPU stats.
func NewStatCollector(logger log.Logger) (Collector, error) { func NewStatCollector(logger *slog.Logger) (Collector, error) {
return &statCollector{ return &statCollector{
cpu: typedDesc{nodeCPUSecondsDesc, prometheus.CounterValue}, cpu: typedDesc{nodeCPUSecondsDesc, prometheus.CounterValue},
temp: typedDesc{prometheus.NewDesc( temp: typedDesc{prometheus.NewDesc(
@ -269,7 +268,7 @@ func (c *statCollector) Update(ch chan<- prometheus.Metric) error {
if temp, ok := cpuTemperatures[cpu]; ok { if temp, ok := cpuTemperatures[cpu]; ok {
ch <- c.temp.mustNewConstMetric(temp, lcpu) ch <- c.temp.mustNewConstMetric(temp, lcpu)
} else { } else {
level.Debug(c.logger).Log("msg", "no temperature information for CPU", "cpu", cpu) c.logger.Debug("no temperature information for CPU", "cpu", cpu)
ch <- c.temp.mustNewConstMetric(math.NaN(), lcpu) ch <- c.temp.mustNewConstMetric(math.NaN(), lcpu)
} }
} }

View file

@ -17,10 +17,10 @@
package collector package collector
import ( import (
"log/slog"
"strconv" "strconv"
"unsafe" "unsafe"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
@ -45,14 +45,14 @@ const (
type cpuCollector struct { type cpuCollector struct {
cpu typedDesc cpu typedDesc
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
registerCollector("cpu", defaultEnabled, NewCPUCollector) registerCollector("cpu", defaultEnabled, NewCPUCollector)
} }
func NewCPUCollector(logger log.Logger) (Collector, error) { func NewCPUCollector(logger *slog.Logger) (Collector, error) {
return &cpuCollector{ return &cpuCollector{
cpu: typedDesc{nodeCPUSecondsDesc, prometheus.CounterValue}, cpu: typedDesc{nodeCPUSecondsDesc, prometheus.CounterValue},
logger: logger, logger: logger,

View file

@ -17,9 +17,9 @@
package collector package collector
import ( import (
"log/slog"
"strconv" "strconv"
"github.com/go-kit/log"
"github.com/illumos/go-kstat" "github.com/illumos/go-kstat"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -29,14 +29,14 @@ import "C"
type cpuCollector struct { type cpuCollector struct {
cpu typedDesc cpu typedDesc
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
registerCollector("cpu", defaultEnabled, NewCpuCollector) registerCollector("cpu", defaultEnabled, NewCpuCollector)
} }
func NewCpuCollector(logger log.Logger) (Collector, error) { func NewCpuCollector(logger *slog.Logger) (Collector, error) {
return &cpuCollector{ return &cpuCollector{
cpu: typedDesc{nodeCPUSecondsDesc, prometheus.CounterValue}, cpu: typedDesc{nodeCPUSecondsDesc, prometheus.CounterValue},
logger: logger, logger: logger,

View file

@ -15,8 +15,8 @@ package collector
import ( import (
"fmt" "fmt"
"log/slog"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/procfs/sysfs" "github.com/prometheus/procfs/sysfs"
) )
@ -40,7 +40,7 @@ func init() {
registerCollector(cpuVulerabilitiesCollector, defaultDisabled, NewVulnerabilitySysfsCollector) registerCollector(cpuVulerabilitiesCollector, defaultDisabled, NewVulnerabilitySysfsCollector)
} }
func NewVulnerabilitySysfsCollector(logger log.Logger) (Collector, error) { func NewVulnerabilitySysfsCollector(logger *slog.Logger) (Collector, error) {
return &cpuVulnerabilitiesCollector{}, nil return &cpuVulnerabilitiesCollector{}, nil
} }

View file

@ -18,15 +18,15 @@ package collector
import ( import (
"fmt" "fmt"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/procfs/sysfs" "github.com/prometheus/procfs/sysfs"
"log/slog"
"strings" "strings"
) )
type cpuFreqCollector struct { type cpuFreqCollector struct {
fs sysfs.FS fs sysfs.FS
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -34,7 +34,7 @@ func init() {
} }
// NewCPUFreqCollector returns a new Collector exposing kernel/system statistics. // NewCPUFreqCollector returns a new Collector exposing kernel/system statistics.
func NewCPUFreqCollector(logger log.Logger) (Collector, error) { func NewCPUFreqCollector(logger *slog.Logger) (Collector, error) {
fs, err := sysfs.NewFS(*sysPath) fs, err := sysfs.NewFS(*sysPath)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to open sysfs: %w", err) return nil, fmt.Errorf("failed to open sysfs: %w", err)

View file

@ -18,9 +18,9 @@ package collector
import ( import (
"fmt" "fmt"
"log/slog"
"strconv" "strconv"
"github.com/go-kit/log"
"github.com/illumos/go-kstat" "github.com/illumos/go-kstat"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -29,14 +29,14 @@ import (
import "C" import "C"
type cpuFreqCollector struct { type cpuFreqCollector struct {
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
registerCollector("cpufreq", defaultEnabled, NewCpuFreqCollector) registerCollector("cpufreq", defaultEnabled, NewCpuFreqCollector)
} }
func NewCpuFreqCollector(logger log.Logger) (Collector, error) { func NewCpuFreqCollector(logger *slog.Logger) (Collector, error) {
return &cpuFreqCollector{ return &cpuFreqCollector{
logger: logger, logger: logger,
}, nil }, nil

View file

@ -19,8 +19,8 @@ package collector
import ( import (
"errors" "errors"
"fmt" "fmt"
"log/slog"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -98,7 +98,7 @@ type devstatCollector struct {
bytesDesc *prometheus.Desc bytesDesc *prometheus.Desc
transfersDesc *prometheus.Desc transfersDesc *prometheus.Desc
blocksDesc *prometheus.Desc blocksDesc *prometheus.Desc
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -106,7 +106,7 @@ func init() {
} }
// NewDevstatCollector returns a new Collector exposing Device stats. // NewDevstatCollector returns a new Collector exposing Device stats.
func NewDevstatCollector(logger log.Logger) (Collector, error) { func NewDevstatCollector(logger *slog.Logger) (Collector, error) {
return &devstatCollector{ return &devstatCollector{
bytesDesc: prometheus.NewDesc( bytesDesc: prometheus.NewDesc(
prometheus.BuildFQName(namespace, devstatSubsystem, "bytes_total"), prometheus.BuildFQName(namespace, devstatSubsystem, "bytes_total"),

View file

@ -19,10 +19,10 @@ package collector
import ( import (
"errors" "errors"
"fmt" "fmt"
"log/slog"
"sync" "sync"
"unsafe" "unsafe"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -43,7 +43,7 @@ type devstatCollector struct {
duration typedDesc duration typedDesc
busyTime typedDesc busyTime typedDesc
blocks typedDesc blocks typedDesc
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -51,7 +51,7 @@ func init() {
} }
// NewDevstatCollector returns a new Collector exposing Device stats. // NewDevstatCollector returns a new Collector exposing Device stats.
func NewDevstatCollector(logger log.Logger) (Collector, error) { func NewDevstatCollector(logger *slog.Logger) (Collector, error) {
return &devstatCollector{ return &devstatCollector{
devinfo: &C.struct_devinfo{}, devinfo: &C.struct_devinfo{},
bytes: typedDesc{prometheus.NewDesc( bytes: typedDesc{prometheus.NewDesc(

View file

@ -19,10 +19,9 @@ package collector
import ( import (
"errors" "errors"
"log/slog"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -93,10 +92,10 @@ var (
) )
) )
func newDiskstatsDeviceFilter(logger log.Logger) (deviceFilter, error) { func newDiskstatsDeviceFilter(logger *slog.Logger) (deviceFilter, error) {
if *oldDiskstatsDeviceExclude != "" { if *oldDiskstatsDeviceExclude != "" {
if !diskstatsDeviceExcludeSet { if !diskstatsDeviceExcludeSet {
level.Warn(logger).Log("msg", "--collector.diskstats.ignored-devices is DEPRECATED and will be removed in 2.0.0, use --collector.diskstats.device-exclude") logger.Warn("--collector.diskstats.ignored-devices is DEPRECATED and will be removed in 2.0.0, use --collector.diskstats.device-exclude")
*diskstatsDeviceExclude = *oldDiskstatsDeviceExclude *diskstatsDeviceExclude = *oldDiskstatsDeviceExclude
} else { } else {
return deviceFilter{}, errors.New("--collector.diskstats.ignored-devices and --collector.diskstats.device-exclude are mutually exclusive") return deviceFilter{}, errors.New("--collector.diskstats.ignored-devices and --collector.diskstats.device-exclude are mutually exclusive")
@ -108,11 +107,11 @@ func newDiskstatsDeviceFilter(logger log.Logger) (deviceFilter, error) {
} }
if *diskstatsDeviceExclude != "" { if *diskstatsDeviceExclude != "" {
level.Info(logger).Log("msg", "Parsed flag --collector.diskstats.device-exclude", "flag", *diskstatsDeviceExclude) logger.Info("Parsed flag --collector.diskstats.device-exclude", "flag", *diskstatsDeviceExclude)
} }
if *diskstatsDeviceInclude != "" { if *diskstatsDeviceInclude != "" {
level.Info(logger).Log("msg", "Parsed Flag --collector.diskstats.device-include", "flag", *diskstatsDeviceInclude) logger.Info("Parsed Flag --collector.diskstats.device-include", "flag", *diskstatsDeviceInclude)
} }
return newDeviceFilter(*diskstatsDeviceExclude, *diskstatsDeviceInclude), nil return newDeviceFilter(*diskstatsDeviceExclude, *diskstatsDeviceInclude), nil

View file

@ -18,8 +18,8 @@ package collector
import ( import (
"fmt" "fmt"
"log/slog"
"github.com/go-kit/log"
"github.com/lufia/iostat" "github.com/lufia/iostat"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -35,7 +35,7 @@ type diskstatsCollector struct {
descs []typedDescFunc descs []typedDescFunc
deviceFilter deviceFilter deviceFilter deviceFilter
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -43,7 +43,7 @@ func init() {
} }
// NewDiskstatsCollector returns a new Collector exposing disk device stats. // NewDiskstatsCollector returns a new Collector exposing disk device stats.
func NewDiskstatsCollector(logger log.Logger) (Collector, error) { func NewDiskstatsCollector(logger *slog.Logger) (Collector, error) {
var diskLabelNames = []string{"device"} var diskLabelNames = []string{"device"}
deviceFilter, err := newDiskstatsDeviceFilter(logger) deviceFilter, err := newDiskstatsDeviceFilter(logger)

View file

@ -19,12 +19,11 @@ package collector
import ( import (
"bufio" "bufio"
"fmt" "fmt"
"log/slog"
"os" "os"
"strconv" "strconv"
"strings" "strings"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/procfs/blockdevice" "github.com/prometheus/procfs/blockdevice"
) )
@ -85,7 +84,7 @@ type diskstatsCollector struct {
filesystemInfoDesc typedFactorDesc filesystemInfoDesc typedFactorDesc
deviceMapperInfoDesc typedFactorDesc deviceMapperInfoDesc typedFactorDesc
ataDescs map[string]typedFactorDesc ataDescs map[string]typedFactorDesc
logger log.Logger logger *slog.Logger
getUdevDeviceProperties func(uint32, uint32) (udevInfo, error) getUdevDeviceProperties func(uint32, uint32) (udevInfo, error)
} }
@ -95,7 +94,7 @@ func init() {
// NewDiskstatsCollector returns a new Collector exposing disk device stats. // NewDiskstatsCollector returns a new Collector exposing disk device stats.
// Docs from https://www.kernel.org/doc/Documentation/iostats.txt // Docs from https://www.kernel.org/doc/Documentation/iostats.txt
func NewDiskstatsCollector(logger log.Logger) (Collector, error) { func NewDiskstatsCollector(logger *slog.Logger) (Collector, error) {
var diskLabelNames = []string{"device"} var diskLabelNames = []string{"device"}
fs, err := blockdevice.NewFS(*procPath, *sysPath) fs, err := blockdevice.NewFS(*procPath, *sysPath)
if err != nil { if err != nil {
@ -262,7 +261,7 @@ func NewDiskstatsCollector(logger log.Logger) (Collector, error) {
// Only enable getting device properties from udev if the directory is readable. // Only enable getting device properties from udev if the directory is readable.
if stat, err := os.Stat(*udevDataPath); err != nil || !stat.IsDir() { if stat, err := os.Stat(*udevDataPath); err != nil || !stat.IsDir() {
level.Error(logger).Log("msg", "Failed to open directory, disabling udev device properties", "path", *udevDataPath) logger.Error("Failed to open directory, disabling udev device properties", "path", *udevDataPath)
} else { } else {
collector.getUdevDeviceProperties = getUdevDeviceProperties collector.getUdevDeviceProperties = getUdevDeviceProperties
} }
@ -284,7 +283,7 @@ func (c *diskstatsCollector) Update(ch chan<- prometheus.Metric) error {
info, err := getUdevDeviceProperties(stats.MajorNumber, stats.MinorNumber) info, err := getUdevDeviceProperties(stats.MajorNumber, stats.MinorNumber)
if err != nil { if err != nil {
level.Debug(c.logger).Log("msg", "Failed to parse udev info", "err", err) c.logger.Debug("Failed to parse udev info", "err", err)
} }
// This is usually the serial printed on the disk label. // This is usually the serial printed on the disk label.
@ -355,14 +354,14 @@ func (c *diskstatsCollector) Update(ch chan<- prometheus.Metric) error {
for attr, desc := range c.ataDescs { for attr, desc := range c.ataDescs {
str, ok := info[attr] str, ok := info[attr]
if !ok { if !ok {
level.Debug(c.logger).Log("msg", "Udev attribute does not exist", "attribute", attr) c.logger.Debug("Udev attribute does not exist", "attribute", attr)
continue continue
} }
if value, err := strconv.ParseFloat(str, 64); err == nil { if value, err := strconv.ParseFloat(str, 64); err == nil {
ch <- desc.mustNewConstMetric(value, dev) ch <- desc.mustNewConstMetric(value, dev)
} else { } else {
level.Error(c.logger).Log("msg", "Failed to parse ATA value", "err", err) c.logger.Error("Failed to parse ATA value", "err", err)
} }
} }
} }

View file

@ -18,11 +18,11 @@ package collector
import ( import (
"fmt" "fmt"
"os" "io"
"log/slog"
"strings" "strings"
"testing" "testing"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/testutil" "github.com/prometheus/client_golang/prometheus/testutil"
) )
@ -39,7 +39,7 @@ func (c testDiskStatsCollector) Describe(ch chan<- *prometheus.Desc) {
prometheus.DescribeByCollect(c, ch) prometheus.DescribeByCollect(c, ch)
} }
func NewTestDiskStatsCollector(logger log.Logger) (prometheus.Collector, error) { func NewTestDiskStatsCollector(logger *slog.Logger) (prometheus.Collector, error) {
dsc, err := NewDiskstatsCollector(logger) dsc, err := NewDiskstatsCollector(logger)
if err != nil { if err != nil {
return testDiskStatsCollector{}, err return testDiskStatsCollector{}, err
@ -317,7 +317,7 @@ node_disk_written_bytes_total{device="sr0"} 0
node_disk_written_bytes_total{device="vda"} 1.0938236928e+11 node_disk_written_bytes_total{device="vda"} 1.0938236928e+11
` `
logger := log.NewLogfmtLogger(os.Stderr) logger := slog.New(slog.NewTextHandler(io.Discard, nil))
collector, err := NewDiskstatsCollector(logger) collector, err := NewDiskstatsCollector(logger)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)

View file

@ -18,9 +18,9 @@ package collector
import ( import (
"fmt" "fmt"
"log/slog"
"unsafe" "unsafe"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
@ -41,7 +41,7 @@ type diskstatsCollector struct {
time typedDesc time typedDesc
deviceFilter deviceFilter deviceFilter deviceFilter
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -49,7 +49,7 @@ func init() {
} }
// NewDiskstatsCollector returns a new Collector exposing disk device stats. // NewDiskstatsCollector returns a new Collector exposing disk device stats.
func NewDiskstatsCollector(logger log.Logger) (Collector, error) { func NewDiskstatsCollector(logger *slog.Logger) (Collector, error) {
deviceFilter, err := newDiskstatsDeviceFilter(logger) deviceFilter, err := newDiskstatsDeviceFilter(logger)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to parse device filter flags: %w", err) return nil, fmt.Errorf("failed to parse device filter flags: %w", err)

View file

@ -18,9 +18,9 @@ package collector
import ( import (
"fmt" "fmt"
"log/slog"
"unsafe" "unsafe"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
@ -52,7 +52,7 @@ type diskstatsCollector struct {
time typedDesc time typedDesc
deviceFilter deviceFilter deviceFilter deviceFilter
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -60,7 +60,7 @@ func init() {
} }
// NewDiskstatsCollector returns a new Collector exposing disk device stats. // NewDiskstatsCollector returns a new Collector exposing disk device stats.
func NewDiskstatsCollector(logger log.Logger) (Collector, error) { func NewDiskstatsCollector(logger *slog.Logger) (Collector, error) {
deviceFilter, err := newDiskstatsDeviceFilter(logger) deviceFilter, err := newDiskstatsDeviceFilter(logger)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to parse device filter flags: %w", err) return nil, fmt.Errorf("failed to parse device filter flags: %w", err)

View file

@ -19,11 +19,10 @@ package collector
import ( import (
"errors" "errors"
"fmt" "fmt"
"log/slog"
"os" "os"
"strings" "strings"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/procfs/sysfs" "github.com/prometheus/procfs/sysfs"
) )
@ -38,7 +37,7 @@ func init() {
} }
// NewDMICollector returns a new Collector exposing DMI information. // NewDMICollector returns a new Collector exposing DMI information.
func NewDMICollector(logger log.Logger) (Collector, error) { func NewDMICollector(logger *slog.Logger) (Collector, error) {
fs, err := sysfs.NewFS(*sysPath) fs, err := sysfs.NewFS(*sysPath)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to open sysfs: %w", err) return nil, fmt.Errorf("failed to open sysfs: %w", err)
@ -47,7 +46,7 @@ func NewDMICollector(logger log.Logger) (Collector, error) {
dmi, err := fs.DMIClass() dmi, err := fs.DMIClass()
if err != nil { if err != nil {
if errors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {
level.Debug(logger).Log("msg", "Platform does not support Desktop Management Interface (DMI) information", "err", err) logger.Debug("Platform does not support Desktop Management Interface (DMI) information", "err", err)
dmi = &sysfs.DMIClass{} dmi = &sysfs.DMIClass{}
} else { } else {
return nil, fmt.Errorf("failed to read Desktop Management Interface (DMI) information: %w", err) return nil, fmt.Errorf("failed to read Desktop Management Interface (DMI) information: %w", err)

View file

@ -20,12 +20,11 @@ import (
"bufio" "bufio"
"errors" "errors"
"fmt" "fmt"
"log/slog"
"os" "os"
"strconv" "strconv"
"strings" "strings"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -79,14 +78,14 @@ type drbdCollector struct {
numerical map[string]drbdNumericalMetric numerical map[string]drbdNumericalMetric
stringPair map[string]drbdStringPairMetric stringPair map[string]drbdStringPairMetric
connected *prometheus.Desc connected *prometheus.Desc
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
registerCollector("drbd", defaultDisabled, newDRBDCollector) registerCollector("drbd", defaultDisabled, newDRBDCollector)
} }
func newDRBDCollector(logger log.Logger) (Collector, error) { func newDRBDCollector(logger *slog.Logger) (Collector, error) {
return &drbdCollector{ return &drbdCollector{
numerical: map[string]drbdNumericalMetric{ numerical: map[string]drbdNumericalMetric{
"ns": newDRBDNumericalMetric( "ns": newDRBDNumericalMetric(
@ -191,7 +190,7 @@ func (c *drbdCollector) Update(ch chan<- prometheus.Metric) error {
file, err := os.Open(statsFile) file, err := os.Open(statsFile)
if err != nil { if err != nil {
if errors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {
level.Debug(c.logger).Log("msg", "stats file does not exist, skipping", "file", statsFile, "err", err) c.logger.Debug("stats file does not exist, skipping", "file", statsFile, "err", err)
return ErrNoData return ErrNoData
} }
@ -208,7 +207,7 @@ func (c *drbdCollector) Update(ch chan<- prometheus.Metric) error {
kv := strings.Split(field, ":") kv := strings.Split(field, ":")
if len(kv) != 2 { if len(kv) != 2 {
level.Debug(c.logger).Log("msg", "skipping invalid key:value pair", "field", field) c.logger.Debug("skipping invalid key:value pair", "field", field)
continue continue
} }
@ -274,7 +273,7 @@ func (c *drbdCollector) Update(ch chan<- prometheus.Metric) error {
continue continue
} }
level.Debug(c.logger).Log("msg", "unhandled key-value pair", "key", kv[0], "value", kv[1]) c.logger.Debug("unhandled key-value pair", "key", kv[0], "value", kv[1])
} }
return scanner.Err() return scanner.Err()

View file

@ -18,8 +18,8 @@ package collector
import ( import (
"fmt" "fmt"
"log/slog"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/procfs/sysfs" "github.com/prometheus/procfs/sysfs"
) )
@ -30,7 +30,7 @@ const (
type drmCollector struct { type drmCollector struct {
fs sysfs.FS fs sysfs.FS
logger log.Logger logger *slog.Logger
CardInfo *prometheus.Desc CardInfo *prometheus.Desc
GPUBusyPercent *prometheus.Desc GPUBusyPercent *prometheus.Desc
MemoryGTTSize *prometheus.Desc MemoryGTTSize *prometheus.Desc
@ -46,7 +46,7 @@ func init() {
} }
// NewDrmCollector returns a new Collector exposing /sys/class/drm/card?/device stats. // NewDrmCollector returns a new Collector exposing /sys/class/drm/card?/device stats.
func NewDrmCollector(logger log.Logger) (Collector, error) { func NewDrmCollector(logger *slog.Logger) (Collector, error) {
fs, err := sysfs.NewFS(*sysPath) fs, err := sysfs.NewFS(*sysPath)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to open sysfs: %w", err) return nil, fmt.Errorf("failed to open sysfs: %w", err)

View file

@ -18,10 +18,10 @@ package collector
import ( import (
"fmt" "fmt"
"log/slog"
"path/filepath" "path/filepath"
"regexp" "regexp"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -39,7 +39,7 @@ type edacCollector struct {
ueCount *prometheus.Desc ueCount *prometheus.Desc
csRowCECount *prometheus.Desc csRowCECount *prometheus.Desc
csRowUECount *prometheus.Desc csRowUECount *prometheus.Desc
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -47,7 +47,7 @@ func init() {
} }
// NewEdacCollector returns a new Collector exposing edac stats. // NewEdacCollector returns a new Collector exposing edac stats.
func NewEdacCollector(logger log.Logger) (Collector, error) { func NewEdacCollector(logger *slog.Logger) (Collector, error) {
return &edacCollector{ return &edacCollector{
ceCount: prometheus.NewDesc( ceCount: prometheus.NewDesc(
prometheus.BuildFQName(namespace, edacSubsystem, "correctable_errors_total"), prometheus.BuildFQName(namespace, edacSubsystem, "correctable_errors_total"),

View file

@ -18,8 +18,8 @@ package collector
import ( import (
"fmt" "fmt"
"log/slog"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/procfs" "github.com/prometheus/procfs"
) )
@ -28,7 +28,7 @@ type entropyCollector struct {
fs procfs.FS fs procfs.FS
entropyAvail *prometheus.Desc entropyAvail *prometheus.Desc
entropyPoolSize *prometheus.Desc entropyPoolSize *prometheus.Desc
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -36,7 +36,7 @@ func init() {
} }
// NewEntropyCollector returns a new Collector exposing entropy stats. // NewEntropyCollector returns a new Collector exposing entropy stats.
func NewEntropyCollector(logger log.Logger) (Collector, error) { func NewEntropyCollector(logger *slog.Logger) (Collector, error) {
fs, err := procfs.NewFS(*procPath) fs, err := procfs.NewFS(*procPath)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to open procfs: %w", err) return nil, fmt.Errorf("failed to open procfs: %w", err)

View file

@ -23,6 +23,7 @@ package collector
import ( import (
"errors" "errors"
"fmt" "fmt"
"log/slog"
"os" "os"
"regexp" "regexp"
"sort" "sort"
@ -31,8 +32,6 @@ import (
"syscall" "syscall"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/procfs/sysfs" "github.com/prometheus/procfs/sysfs"
"github.com/safchain/ethtool" "github.com/safchain/ethtool"
@ -79,13 +78,13 @@ type ethtoolCollector struct {
deviceFilter deviceFilter deviceFilter deviceFilter
infoDesc *prometheus.Desc infoDesc *prometheus.Desc
metricsPattern *regexp.Regexp metricsPattern *regexp.Regexp
logger log.Logger logger *slog.Logger
} }
// makeEthtoolCollector is the internal constructor for EthtoolCollector. // makeEthtoolCollector is the internal constructor for EthtoolCollector.
// This allows NewEthtoolTestCollector to override its .ethtool interface // This allows NewEthtoolTestCollector to override its .ethtool interface
// for testing. // for testing.
func makeEthtoolCollector(logger log.Logger) (*ethtoolCollector, error) { func makeEthtoolCollector(logger *slog.Logger) (*ethtoolCollector, error) {
fs, err := sysfs.NewFS(*sysPath) fs, err := sysfs.NewFS(*sysPath)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to open sysfs: %w", err) return nil, fmt.Errorf("failed to open sysfs: %w", err)
@ -97,13 +96,13 @@ func makeEthtoolCollector(logger log.Logger) (*ethtoolCollector, error) {
} }
if *ethtoolDeviceInclude != "" { if *ethtoolDeviceInclude != "" {
level.Info(logger).Log("msg", "Parsed flag --collector.ethtool.device-include", "flag", *ethtoolDeviceInclude) logger.Info("Parsed flag --collector.ethtool.device-include", "flag", *ethtoolDeviceInclude)
} }
if *ethtoolDeviceExclude != "" { if *ethtoolDeviceExclude != "" {
level.Info(logger).Log("msg", "Parsed flag --collector.ethtool.device-exclude", "flag", *ethtoolDeviceExclude) logger.Info("Parsed flag --collector.ethtool.device-exclude", "flag", *ethtoolDeviceExclude)
} }
if *ethtoolIncludedMetrics != "" { if *ethtoolIncludedMetrics != "" {
level.Info(logger).Log("msg", "Parsed flag --collector.ethtool.metrics-include", "flag", *ethtoolIncludedMetrics) logger.Info("Parsed flag --collector.ethtool.metrics-include", "flag", *ethtoolIncludedMetrics)
} }
// Pre-populate some common ethtool metrics. // Pre-populate some common ethtool metrics.
@ -223,7 +222,7 @@ func buildEthtoolFQName(metric string) string {
} }
// NewEthtoolCollector returns a new Collector exposing ethtool stats. // NewEthtoolCollector returns a new Collector exposing ethtool stats.
func NewEthtoolCollector(logger log.Logger) (Collector, error) { func NewEthtoolCollector(logger *slog.Logger) (Collector, error) {
return makeEthtoolCollector(logger) return makeEthtoolCollector(logger)
} }
@ -376,7 +375,7 @@ func (c *ethtoolCollector) Update(ch chan<- prometheus.Metric) error {
netClass, err := c.fs.NetClass() netClass, err := c.fs.NetClass()
if err != nil { if err != nil {
if errors.Is(err, os.ErrNotExist) || errors.Is(err, os.ErrPermission) { if errors.Is(err, os.ErrNotExist) || errors.Is(err, os.ErrPermission) {
level.Debug(c.logger).Log("msg", "Could not read netclass file", "err", err) c.logger.Debug("Could not read netclass file", "err", err)
return ErrNoData return ErrNoData
} }
return fmt.Errorf("could not get net class info: %w", err) return fmt.Errorf("could not get net class info: %w", err)
@ -405,12 +404,12 @@ func (c *ethtoolCollector) Update(ch chan<- prometheus.Metric) error {
} else { } else {
if errno, ok := err.(syscall.Errno); ok { if errno, ok := err.(syscall.Errno); ok {
if err == unix.EOPNOTSUPP { if err == unix.EOPNOTSUPP {
level.Debug(c.logger).Log("msg", "ethtool link info error", "err", err, "device", device, "errno", uint(errno)) c.logger.Debug("ethtool link info error", "err", err, "device", device, "errno", uint(errno))
} else if errno != 0 { } else if errno != 0 {
level.Error(c.logger).Log("msg", "ethtool link info error", "err", err, "device", device, "errno", uint(errno)) c.logger.Error("ethtool link info error", "err", err, "device", device, "errno", uint(errno))
} }
} else { } else {
level.Error(c.logger).Log("msg", "ethtool link info error", "err", err, "device", device) c.logger.Error("ethtool link info error", "err", err, "device", device)
} }
} }
@ -422,12 +421,12 @@ func (c *ethtoolCollector) Update(ch chan<- prometheus.Metric) error {
} else { } else {
if errno, ok := err.(syscall.Errno); ok { if errno, ok := err.(syscall.Errno); ok {
if err == unix.EOPNOTSUPP { if err == unix.EOPNOTSUPP {
level.Debug(c.logger).Log("msg", "ethtool driver info error", "err", err, "device", device, "errno", uint(errno)) c.logger.Debug("ethtool driver info error", "err", err, "device", device, "errno", uint(errno))
} else if errno != 0 { } else if errno != 0 {
level.Error(c.logger).Log("msg", "ethtool driver info error", "err", err, "device", device, "errno", uint(errno)) c.logger.Error("ethtool driver info error", "err", err, "device", device, "errno", uint(errno))
} }
} else { } else {
level.Error(c.logger).Log("msg", "ethtool driver info error", "err", err, "device", device) c.logger.Error("ethtool driver info error", "err", err, "device", device)
} }
} }
@ -438,12 +437,12 @@ func (c *ethtoolCollector) Update(ch chan<- prometheus.Metric) error {
if err != nil { if err != nil {
if errno, ok := err.(syscall.Errno); ok { if errno, ok := err.(syscall.Errno); ok {
if err == unix.EOPNOTSUPP { if err == unix.EOPNOTSUPP {
level.Debug(c.logger).Log("msg", "ethtool stats error", "err", err, "device", device, "errno", uint(errno)) c.logger.Debug("ethtool stats error", "err", err, "device", device, "errno", uint(errno))
} else if errno != 0 { } else if errno != 0 {
level.Error(c.logger).Log("msg", "ethtool stats error", "err", err, "device", device, "errno", uint(errno)) c.logger.Error("ethtool stats error", "err", err, "device", device, "errno", uint(errno))
} }
} else { } else {
level.Error(c.logger).Log("msg", "ethtool stats error", "err", err, "device", device) c.logger.Error("ethtool stats error", "err", err, "device", device)
} }
} }
@ -462,7 +461,7 @@ func (c *ethtoolCollector) Update(ch chan<- prometheus.Metric) error {
metricFQName := buildEthtoolFQName(metricName) metricFQName := buildEthtoolFQName(metricName)
existingMetric, exists := metricFQNames[metricFQName] existingMetric, exists := metricFQNames[metricFQName]
if exists { if exists {
level.Debug(c.logger).Log("msg", "dropping duplicate metric name", "device", device, c.logger.Debug("dropping duplicate metric name", "device", device,
"metricFQName", metricFQName, "metric1", existingMetric, "metric2", metricName) "metricFQName", metricFQName, "metric1", existingMetric, "metric2", metricName)
// Keep the metricName as "deleted" in the dict in case there are 3 duplicates. // Keep the metricName as "deleted" in the dict in case there are 3 duplicates.
metricFQNames[metricFQName] = "" metricFQNames[metricFQName] = ""

View file

@ -19,6 +19,8 @@ package collector
import ( import (
"bufio" "bufio"
"fmt" "fmt"
"io"
"log/slog"
"os" "os"
"path/filepath" "path/filepath"
"strconv" "strconv"
@ -26,7 +28,6 @@ import (
"syscall" "syscall"
"testing" "testing"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/testutil" "github.com/prometheus/client_golang/prometheus/testutil"
"github.com/safchain/ethtool" "github.com/safchain/ethtool"
@ -49,7 +50,7 @@ func (c testEthtoolCollector) Describe(ch chan<- *prometheus.Desc) {
prometheus.DescribeByCollect(c, ch) prometheus.DescribeByCollect(c, ch)
} }
func NewTestEthtoolCollector(logger log.Logger) (prometheus.Collector, error) { func NewTestEthtoolCollector(logger *slog.Logger) (prometheus.Collector, error) {
dsc, err := NewEthtoolTestCollector(logger) dsc, err := NewEthtoolTestCollector(logger)
if err != nil { if err != nil {
return testEthtoolCollector{}, err return testEthtoolCollector{}, err
@ -255,7 +256,7 @@ func (e *EthtoolFixture) LinkInfo(intf string) (ethtool.EthtoolCmd, error) {
return res, err return res, err
} }
func NewEthtoolTestCollector(logger log.Logger) (Collector, error) { func NewEthtoolTestCollector(logger *slog.Logger) (Collector, error) {
collector, err := makeEthtoolCollector(logger) collector, err := makeEthtoolCollector(logger)
if err != nil { if err != nil {
return nil, err return nil, err
@ -370,7 +371,7 @@ node_network_supported_speed_bytes{device="eth0",duplex="half",mode="10baseT"} 1
` `
*sysPath = "fixtures/sys" *sysPath = "fixtures/sys"
logger := log.NewLogfmtLogger(os.Stderr) logger := slog.New(slog.NewTextHandler(io.Discard, nil))
collector, err := NewEthtoolTestCollector(logger) collector, err := NewEthtoolTestCollector(logger)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)

View file

@ -18,13 +18,13 @@
package collector package collector
import ( import (
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"log/slog"
) )
type execCollector struct { type execCollector struct {
sysctls []bsdSysctl sysctls []bsdSysctl
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -32,7 +32,7 @@ func init() {
} }
// NewExecCollector returns a new Collector exposing system execution statistics. // NewExecCollector returns a new Collector exposing system execution statistics.
func NewExecCollector(logger log.Logger) (Collector, error) { func NewExecCollector(logger *slog.Logger) (Collector, error) {
// From sys/vm/vm_meter.c: // From sys/vm/vm_meter.c:
// All are of type CTLTYPE_UINT. // All are of type CTLTYPE_UINT.
// //

View file

@ -18,10 +18,9 @@ package collector
import ( import (
"fmt" "fmt"
"log/slog"
"os" "os"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/node_exporter/collector/utils" "github.com/prometheus/node_exporter/collector/utils"
"github.com/prometheus/procfs/sysfs" "github.com/prometheus/procfs/sysfs"
@ -32,7 +31,7 @@ const maxUint64 = ^uint64(0)
type fibrechannelCollector struct { type fibrechannelCollector struct {
fs sysfs.FS fs sysfs.FS
metricDescs map[string]*prometheus.Desc metricDescs map[string]*prometheus.Desc
logger log.Logger logger *slog.Logger
subsystem string subsystem string
} }
@ -41,7 +40,7 @@ func init() {
} }
// NewFibreChannelCollector returns a new Collector exposing FibreChannel stats. // NewFibreChannelCollector returns a new Collector exposing FibreChannel stats.
func NewFibreChannelCollector(logger log.Logger) (Collector, error) { func NewFibreChannelCollector(logger *slog.Logger) (Collector, error) {
var i fibrechannelCollector var i fibrechannelCollector
var err error var err error
@ -99,7 +98,7 @@ func (c *fibrechannelCollector) Update(ch chan<- prometheus.Metric) error {
hosts, err := c.fs.FibreChannelClass() hosts, err := c.fs.FibreChannelClass()
if err != nil { if err != nil {
if os.IsNotExist(err) { if os.IsNotExist(err) {
level.Debug(c.logger).Log("msg", "fibrechannel statistics not found, skipping") c.logger.Debug("fibrechannel statistics not found, skipping")
return ErrNoData return ErrNoData
} }
return fmt.Errorf("error obtaining FibreChannel class info: %s", err) return fmt.Errorf("error obtaining FibreChannel class info: %s", err)

View file

@ -20,10 +20,10 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"io" "io"
"log/slog"
"os" "os"
"strconv" "strconv"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -32,7 +32,7 @@ const (
) )
type fileFDStatCollector struct { type fileFDStatCollector struct {
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -40,7 +40,7 @@ func init() {
} }
// NewFileFDStatCollector returns a new Collector exposing file-nr stats. // NewFileFDStatCollector returns a new Collector exposing file-nr stats.
func NewFileFDStatCollector(logger log.Logger) (Collector, error) { func NewFileFDStatCollector(logger *slog.Logger) (Collector, error) {
return &fileFDStatCollector{logger}, nil return &fileFDStatCollector{logger}, nil
} }

View file

@ -20,8 +20,6 @@ package collector
import ( import (
"errors" "errors"
"unsafe" "unsafe"
"github.com/go-kit/log/level"
) )
/* /*
@ -51,14 +49,14 @@ func (c *filesystemCollector) GetStats() (stats []filesystemStats, err error) {
for i := 0; i < int(count); i++ { for i := 0; i < int(count); i++ {
mountpoint := C.GoString(&mnt[i].f_mntonname[0]) mountpoint := C.GoString(&mnt[i].f_mntonname[0])
if c.excludedMountPointsPattern.MatchString(mountpoint) { if c.excludedMountPointsPattern.MatchString(mountpoint) {
level.Debug(c.logger).Log("msg", "Ignoring mount point", "mountpoint", mountpoint) c.logger.Debug("Ignoring mount point", "mountpoint", mountpoint)
continue continue
} }
device := C.GoString(&mnt[i].f_mntfromname[0]) device := C.GoString(&mnt[i].f_mntfromname[0])
fstype := C.GoString(&mnt[i].f_fstypename[0]) fstype := C.GoString(&mnt[i].f_fstypename[0])
if c.excludedFSTypesPattern.MatchString(fstype) { if c.excludedFSTypesPattern.MatchString(fstype) {
level.Debug(c.logger).Log("msg", "Ignoring fs type", "type", fstype) c.logger.Debug("Ignoring fs type", "type", fstype)
continue continue
} }

View file

@ -19,11 +19,10 @@ package collector
import ( import (
"errors" "errors"
"log/slog"
"regexp" "regexp"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -70,7 +69,7 @@ type filesystemCollector struct {
filesDesc, filesFreeDesc *prometheus.Desc filesDesc, filesFreeDesc *prometheus.Desc
roDesc, deviceErrorDesc *prometheus.Desc roDesc, deviceErrorDesc *prometheus.Desc
mountInfoDesc *prometheus.Desc mountInfoDesc *prometheus.Desc
logger log.Logger logger *slog.Logger
} }
type filesystemLabels struct { type filesystemLabels struct {
@ -89,10 +88,10 @@ func init() {
} }
// NewFilesystemCollector returns a new Collector exposing filesystems stats. // NewFilesystemCollector returns a new Collector exposing filesystems stats.
func NewFilesystemCollector(logger log.Logger) (Collector, error) { func NewFilesystemCollector(logger *slog.Logger) (Collector, error) {
if *oldMountPointsExcluded != "" { if *oldMountPointsExcluded != "" {
if !mountPointsExcludeSet { if !mountPointsExcludeSet {
level.Warn(logger).Log("msg", "--collector.filesystem.ignored-mount-points is DEPRECATED and will be removed in 2.0.0, use --collector.filesystem.mount-points-exclude") logger.Warn("--collector.filesystem.ignored-mount-points is DEPRECATED and will be removed in 2.0.0, use --collector.filesystem.mount-points-exclude")
*mountPointsExclude = *oldMountPointsExcluded *mountPointsExclude = *oldMountPointsExcluded
} else { } else {
return nil, errors.New("--collector.filesystem.ignored-mount-points and --collector.filesystem.mount-points-exclude are mutually exclusive") return nil, errors.New("--collector.filesystem.ignored-mount-points and --collector.filesystem.mount-points-exclude are mutually exclusive")
@ -101,7 +100,7 @@ func NewFilesystemCollector(logger log.Logger) (Collector, error) {
if *oldFSTypesExcluded != "" { if *oldFSTypesExcluded != "" {
if !fsTypesExcludeSet { if !fsTypesExcludeSet {
level.Warn(logger).Log("msg", "--collector.filesystem.ignored-fs-types is DEPRECATED and will be removed in 2.0.0, use --collector.filesystem.fs-types-exclude") logger.Warn("--collector.filesystem.ignored-fs-types is DEPRECATED and will be removed in 2.0.0, use --collector.filesystem.fs-types-exclude")
*fsTypesExclude = *oldFSTypesExcluded *fsTypesExclude = *oldFSTypesExcluded
} else { } else {
return nil, errors.New("--collector.filesystem.ignored-fs-types and --collector.filesystem.fs-types-exclude are mutually exclusive") return nil, errors.New("--collector.filesystem.ignored-fs-types and --collector.filesystem.fs-types-exclude are mutually exclusive")
@ -109,9 +108,9 @@ func NewFilesystemCollector(logger log.Logger) (Collector, error) {
} }
subsystem := "filesystem" subsystem := "filesystem"
level.Info(logger).Log("msg", "Parsed flag --collector.filesystem.mount-points-exclude", "flag", *mountPointsExclude) logger.Info("Parsed flag --collector.filesystem.mount-points-exclude", "flag", *mountPointsExclude)
mountPointPattern := regexp.MustCompile(*mountPointsExclude) mountPointPattern := regexp.MustCompile(*mountPointsExclude)
level.Info(logger).Log("msg", "Parsed flag --collector.filesystem.fs-types-exclude", "flag", *fsTypesExclude) logger.Info("Parsed flag --collector.filesystem.fs-types-exclude", "flag", *fsTypesExclude)
filesystemsTypesPattern := regexp.MustCompile(*fsTypesExclude) filesystemsTypesPattern := regexp.MustCompile(*fsTypesExclude)
sizeDesc := prometheus.NewDesc( sizeDesc := prometheus.NewDesc(

View file

@ -17,7 +17,6 @@
package collector package collector
import ( import (
"github.com/go-kit/log/level"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
@ -41,19 +40,19 @@ func (c *filesystemCollector) GetStats() ([]filesystemStats, error) {
for _, fs := range buf { for _, fs := range buf {
mountpoint := unix.ByteSliceToString(fs.Mntonname[:]) mountpoint := unix.ByteSliceToString(fs.Mntonname[:])
if c.excludedMountPointsPattern.MatchString(mountpoint) { if c.excludedMountPointsPattern.MatchString(mountpoint) {
level.Debug(c.logger).Log("msg", "Ignoring mount point", "mountpoint", mountpoint) c.logger.Debug("Ignoring mount point", "mountpoint", mountpoint)
continue continue
} }
device := unix.ByteSliceToString(fs.Mntfromname[:]) device := unix.ByteSliceToString(fs.Mntfromname[:])
fstype := unix.ByteSliceToString(fs.Fstypename[:]) fstype := unix.ByteSliceToString(fs.Fstypename[:])
if c.excludedFSTypesPattern.MatchString(fstype) { if c.excludedFSTypesPattern.MatchString(fstype) {
level.Debug(c.logger).Log("msg", "Ignoring fs type", "type", fstype) c.logger.Debug("Ignoring fs type", "type", fstype)
continue continue
} }
if (fs.Flags & unix.MNT_IGNORE) != 0 { if (fs.Flags & unix.MNT_IGNORE) != 0 {
level.Debug(c.logger).Log("msg", "Ignoring mount flagged as ignore", "mountpoint", mountpoint) c.logger.Debug("Ignoring mount flagged as ignore", "mountpoint", mountpoint)
continue continue
} }

View file

@ -21,14 +21,13 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"log/slog"
"os" "os"
"strings" "strings"
"sync" "sync"
"time" "time"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
@ -75,11 +74,11 @@ func (c *filesystemCollector) GetStats() ([]filesystemStats, error) {
go func() { go func() {
for _, labels := range mps { for _, labels := range mps {
if c.excludedMountPointsPattern.MatchString(labels.mountPoint) { if c.excludedMountPointsPattern.MatchString(labels.mountPoint) {
level.Debug(c.logger).Log("msg", "Ignoring mount point", "mountpoint", labels.mountPoint) c.logger.Debug("Ignoring mount point", "mountpoint", labels.mountPoint)
continue continue
} }
if c.excludedFSTypesPattern.MatchString(labels.fsType) { if c.excludedFSTypesPattern.MatchString(labels.fsType) {
level.Debug(c.logger).Log("msg", "Ignoring fs", "type", labels.fsType) c.logger.Debug("Ignoring fs", "type", labels.fsType)
continue continue
} }
@ -90,7 +89,7 @@ func (c *filesystemCollector) GetStats() ([]filesystemStats, error) {
labels: labels, labels: labels,
deviceError: 1, deviceError: 1,
}) })
level.Debug(c.logger).Log("msg", "Mount point is in an unresponsive state", "mountpoint", labels.mountPoint) c.logger.Debug("Mount point is in an unresponsive state", "mountpoint", labels.mountPoint)
stuckMountsMtx.Unlock() stuckMountsMtx.Unlock()
continue continue
} }
@ -128,14 +127,14 @@ func (c *filesystemCollector) processStat(labels filesystemLabels) filesystemSta
// If the mount has been marked as stuck, unmark it and log it's recovery. // If the mount has been marked as stuck, unmark it and log it's recovery.
if _, ok := stuckMounts[labels.mountPoint]; ok { if _, ok := stuckMounts[labels.mountPoint]; ok {
level.Debug(c.logger).Log("msg", "Mount point has recovered, monitoring will resume", "mountpoint", labels.mountPoint) c.logger.Debug("Mount point has recovered, monitoring will resume", "mountpoint", labels.mountPoint)
delete(stuckMounts, labels.mountPoint) delete(stuckMounts, labels.mountPoint)
} }
stuckMountsMtx.Unlock() stuckMountsMtx.Unlock()
if err != nil { if err != nil {
labels.deviceError = err.Error() labels.deviceError = err.Error()
level.Debug(c.logger).Log("msg", "Error on statfs() system call", "rootfs", rootfsFilePath(labels.mountPoint), "err", err) c.logger.Debug("Error on statfs() system call", "rootfs", rootfsFilePath(labels.mountPoint), "err", err)
return filesystemStats{ return filesystemStats{
labels: labels, labels: labels,
deviceError: 1, deviceError: 1,
@ -157,7 +156,7 @@ func (c *filesystemCollector) processStat(labels filesystemLabels) filesystemSta
// stuckMountWatcher listens on the given success channel and if the channel closes // stuckMountWatcher listens on the given success channel and if the channel closes
// then the watcher does nothing. If instead the timeout is reached, the // then the watcher does nothing. If instead the timeout is reached, the
// mount point that is being watched is marked as stuck. // mount point that is being watched is marked as stuck.
func stuckMountWatcher(mountPoint string, success chan struct{}, logger log.Logger) { func stuckMountWatcher(mountPoint string, success chan struct{}, logger *slog.Logger) {
mountCheckTimer := time.NewTimer(*mountTimeout) mountCheckTimer := time.NewTimer(*mountTimeout)
defer mountCheckTimer.Stop() defer mountCheckTimer.Stop()
select { select {
@ -170,18 +169,18 @@ func stuckMountWatcher(mountPoint string, success chan struct{}, logger log.Logg
case <-success: case <-success:
// Success came in just after the timeout was reached, don't label the mount as stuck // Success came in just after the timeout was reached, don't label the mount as stuck
default: default:
level.Debug(logger).Log("msg", "Mount point timed out, it is being labeled as stuck and will not be monitored", "mountpoint", mountPoint) logger.Debug("Mount point timed out, it is being labeled as stuck and will not be monitored", "mountpoint", mountPoint)
stuckMounts[mountPoint] = struct{}{} stuckMounts[mountPoint] = struct{}{}
} }
stuckMountsMtx.Unlock() stuckMountsMtx.Unlock()
} }
} }
func mountPointDetails(logger log.Logger) ([]filesystemLabels, error) { func mountPointDetails(logger *slog.Logger) ([]filesystemLabels, error) {
file, err := os.Open(procFilePath("1/mountinfo")) file, err := os.Open(procFilePath("1/mountinfo"))
if errors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {
// Fallback to `/proc/self/mountinfo` if `/proc/1/mountinfo` is missing due hidepid. // Fallback to `/proc/self/mountinfo` if `/proc/1/mountinfo` is missing due hidepid.
level.Debug(logger).Log("msg", "Reading root mounts failed, falling back to self mounts", "err", err) logger.Debug("Reading root mounts failed, falling back to self mounts", "err", err)
file, err = os.Open(procFilePath("self/mountinfo")) file, err = os.Open(procFilePath("self/mountinfo"))
} }
if err != nil { if err != nil {

View file

@ -17,11 +17,12 @@
package collector package collector
import ( import (
"io"
"log/slog"
"strings" "strings"
"testing" "testing"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
) )
func Test_parseFilesystemLabelsError(t *testing.T) { func Test_parseFilesystemLabelsError(t *testing.T) {
@ -82,7 +83,7 @@ func TestMountPointDetails(t *testing.T) {
"/var/lib/kubelet/plugins/kubernetes.io/vsphere-volume/mounts/[vsanDatastore] bafb9e5a-8856-7e6c-699c-801844e77a4a/kubernetes-dynamic-pvc-3eba5bba-48a3-11e8-89ab-005056b92113.vmdk": "", "/var/lib/kubelet/plugins/kubernetes.io/vsphere-volume/mounts/[vsanDatastore] bafb9e5a-8856-7e6c-699c-801844e77a4a/kubernetes-dynamic-pvc-3eba5bba-48a3-11e8-89ab-005056b92113.vmdk": "",
} }
filesystems, err := mountPointDetails(log.NewNopLogger()) filesystems, err := mountPointDetails(slog.New(slog.NewTextHandler(io.Discard, nil)))
if err != nil { if err != nil {
t.Log(err) t.Log(err)
} }
@ -111,7 +112,7 @@ func TestMountsFallback(t *testing.T) {
"/": "", "/": "",
} }
filesystems, err := mountPointDetails(log.NewNopLogger()) filesystems, err := mountPointDetails(slog.New(slog.NewTextHandler(io.Discard, nil)))
if err != nil { if err != nil {
t.Log(err) t.Log(err)
} }
@ -139,7 +140,7 @@ func TestPathRootfs(t *testing.T) {
"/sys/fs/cgroup": "", "/sys/fs/cgroup": "",
} }
filesystems, err := mountPointDetails(log.NewNopLogger()) filesystems, err := mountPointDetails(slog.New(slog.NewTextHandler(io.Discard, nil)))
if err != nil { if err != nil {
t.Log(err) t.Log(err)
} }

View file

@ -17,7 +17,6 @@
package collector package collector
import ( import (
"github.com/go-kit/log/level"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
@ -43,14 +42,14 @@ func (c *filesystemCollector) GetStats() (stats []filesystemStats, err error) {
for _, v := range mnt { for _, v := range mnt {
mountpoint := unix.ByteSliceToString(v.F_mntonname[:]) mountpoint := unix.ByteSliceToString(v.F_mntonname[:])
if c.excludedMountPointsPattern.MatchString(mountpoint) { if c.excludedMountPointsPattern.MatchString(mountpoint) {
level.Debug(c.logger).Log("msg", "Ignoring mount point", "mountpoint", mountpoint) c.logger.Debug("Ignoring mount point", "mountpoint", mountpoint)
continue continue
} }
device := unix.ByteSliceToString(v.F_mntfromname[:]) device := unix.ByteSliceToString(v.F_mntfromname[:])
fstype := unix.ByteSliceToString(v.F_fstypename[:]) fstype := unix.ByteSliceToString(v.F_fstypename[:])
if c.excludedFSTypesPattern.MatchString(fstype) { if c.excludedFSTypesPattern.MatchString(fstype) {
level.Debug(c.logger).Log("msg", "Ignoring fs type", "type", fstype) c.logger.Debug("Ignoring fs type", "type", fstype)
continue continue
} }

View file

@ -1,55 +1,59 @@
# HELP go_gc_duration_seconds A summary of the pause duration of garbage collection cycles. # HELP go_gc_duration_seconds A summary of the wall-time pause (stop-the-world) duration in garbage collection cycles.
# TYPE go_gc_duration_seconds summary # TYPE go_gc_duration_seconds summary
# HELP go_gc_gogc_percent Heap size target percentage configured by the user, otherwise 100. This value is set by the GOGC environment variable, and the runtime/debug.SetGCPercent function. Sourced from /gc/gogc:percent
# TYPE go_gc_gogc_percent gauge
# HELP go_gc_gomemlimit_bytes Go runtime memory limit configured by the user, otherwise math.MaxInt64. This value is set by the GOMEMLIMIT environment variable, and the runtime/debug.SetMemoryLimit function. Sourced from /gc/gomemlimit:bytes
# TYPE go_gc_gomemlimit_bytes gauge
# HELP go_goroutines Number of goroutines that currently exist. # HELP go_goroutines Number of goroutines that currently exist.
# TYPE go_goroutines gauge # TYPE go_goroutines gauge
# HELP go_info Information about the Go environment. # HELP go_info Information about the Go environment.
# TYPE go_info gauge # TYPE go_info gauge
# HELP go_memstats_alloc_bytes Number of bytes allocated and still in use. # HELP go_memstats_alloc_bytes Number of bytes allocated in heap and currently in use. Equals to /memory/classes/heap/objects:bytes.
# TYPE go_memstats_alloc_bytes gauge # TYPE go_memstats_alloc_bytes gauge
# HELP go_memstats_alloc_bytes_total Total number of bytes allocated, even if freed. # HELP go_memstats_alloc_bytes_total Total number of bytes allocated in heap until now, even if released already. Equals to /gc/heap/allocs:bytes.
# TYPE go_memstats_alloc_bytes_total counter # TYPE go_memstats_alloc_bytes_total counter
# HELP go_memstats_buck_hash_sys_bytes Number of bytes used by the profiling bucket hash table. # HELP go_memstats_buck_hash_sys_bytes Number of bytes used by the profiling bucket hash table. Equals to /memory/classes/profiling/buckets:bytes.
# TYPE go_memstats_buck_hash_sys_bytes gauge # TYPE go_memstats_buck_hash_sys_bytes gauge
# HELP go_memstats_frees_total Total number of frees. # HELP go_memstats_frees_total Total number of heap objects frees. Equals to /gc/heap/frees:objects + /gc/heap/tiny/allocs:objects.
# TYPE go_memstats_frees_total counter # TYPE go_memstats_frees_total counter
# HELP go_memstats_gc_sys_bytes Number of bytes used for garbage collection system metadata. # HELP go_memstats_gc_sys_bytes Number of bytes used for garbage collection system metadata. Equals to /memory/classes/metadata/other:bytes.
# TYPE go_memstats_gc_sys_bytes gauge # TYPE go_memstats_gc_sys_bytes gauge
# HELP go_memstats_heap_alloc_bytes Number of heap bytes allocated and still in use. # HELP go_memstats_heap_alloc_bytes Number of heap bytes allocated and currently in use, same as go_memstats_alloc_bytes. Equals to /memory/classes/heap/objects:bytes.
# TYPE go_memstats_heap_alloc_bytes gauge # TYPE go_memstats_heap_alloc_bytes gauge
# HELP go_memstats_heap_idle_bytes Number of heap bytes waiting to be used. # HELP go_memstats_heap_idle_bytes Number of heap bytes waiting to be used. Equals to /memory/classes/heap/released:bytes + /memory/classes/heap/free:bytes.
# TYPE go_memstats_heap_idle_bytes gauge # TYPE go_memstats_heap_idle_bytes gauge
# HELP go_memstats_heap_inuse_bytes Number of heap bytes that are in use. # HELP go_memstats_heap_inuse_bytes Number of heap bytes that are in use. Equals to /memory/classes/heap/objects:bytes + /memory/classes/heap/unused:bytes
# TYPE go_memstats_heap_inuse_bytes gauge # TYPE go_memstats_heap_inuse_bytes gauge
# HELP go_memstats_heap_objects Number of allocated objects. # HELP go_memstats_heap_objects Number of currently allocated objects. Equals to /gc/heap/objects:objects.
# TYPE go_memstats_heap_objects gauge # TYPE go_memstats_heap_objects gauge
# HELP go_memstats_heap_released_bytes Number of heap bytes released to OS. # HELP go_memstats_heap_released_bytes Number of heap bytes released to OS. Equals to /memory/classes/heap/released:bytes.
# TYPE go_memstats_heap_released_bytes gauge # TYPE go_memstats_heap_released_bytes gauge
# HELP go_memstats_heap_sys_bytes Number of heap bytes obtained from system. # HELP go_memstats_heap_sys_bytes Number of heap bytes obtained from system. Equals to /memory/classes/heap/objects:bytes + /memory/classes/heap/unused:bytes + /memory/classes/heap/released:bytes + /memory/classes/heap/free:bytes.
# TYPE go_memstats_heap_sys_bytes gauge # TYPE go_memstats_heap_sys_bytes gauge
# HELP go_memstats_last_gc_time_seconds Number of seconds since 1970 of last garbage collection. # HELP go_memstats_last_gc_time_seconds Number of seconds since 1970 of last garbage collection.
# TYPE go_memstats_last_gc_time_seconds gauge # TYPE go_memstats_last_gc_time_seconds gauge
# HELP go_memstats_lookups_total Total number of pointer lookups. # HELP go_memstats_mallocs_total Total number of heap objects allocated, both live and gc-ed. Semantically a counter version for go_memstats_heap_objects gauge. Equals to /gc/heap/allocs:objects + /gc/heap/tiny/allocs:objects.
# TYPE go_memstats_lookups_total counter
# HELP go_memstats_mallocs_total Total number of mallocs.
# TYPE go_memstats_mallocs_total counter # TYPE go_memstats_mallocs_total counter
# HELP go_memstats_mcache_inuse_bytes Number of bytes in use by mcache structures. # HELP go_memstats_mcache_inuse_bytes Number of bytes in use by mcache structures. Equals to /memory/classes/metadata/mcache/inuse:bytes.
# TYPE go_memstats_mcache_inuse_bytes gauge # TYPE go_memstats_mcache_inuse_bytes gauge
# HELP go_memstats_mcache_sys_bytes Number of bytes used for mcache structures obtained from system. # HELP go_memstats_mcache_sys_bytes Number of bytes used for mcache structures obtained from system. Equals to /memory/classes/metadata/mcache/inuse:bytes + /memory/classes/metadata/mcache/free:bytes.
# TYPE go_memstats_mcache_sys_bytes gauge # TYPE go_memstats_mcache_sys_bytes gauge
# HELP go_memstats_mspan_inuse_bytes Number of bytes in use by mspan structures. # HELP go_memstats_mspan_inuse_bytes Number of bytes in use by mspan structures. Equals to /memory/classes/metadata/mspan/inuse:bytes.
# TYPE go_memstats_mspan_inuse_bytes gauge # TYPE go_memstats_mspan_inuse_bytes gauge
# HELP go_memstats_mspan_sys_bytes Number of bytes used for mspan structures obtained from system. # HELP go_memstats_mspan_sys_bytes Number of bytes used for mspan structures obtained from system. Equals to /memory/classes/metadata/mspan/inuse:bytes + /memory/classes/metadata/mspan/free:bytes.
# TYPE go_memstats_mspan_sys_bytes gauge # TYPE go_memstats_mspan_sys_bytes gauge
# HELP go_memstats_next_gc_bytes Number of heap bytes when next garbage collection will take place. # HELP go_memstats_next_gc_bytes Number of heap bytes when next garbage collection will take place. Equals to /gc/heap/goal:bytes.
# TYPE go_memstats_next_gc_bytes gauge # TYPE go_memstats_next_gc_bytes gauge
# HELP go_memstats_other_sys_bytes Number of bytes used for other system allocations. # HELP go_memstats_other_sys_bytes Number of bytes used for other system allocations. Equals to /memory/classes/other:bytes.
# TYPE go_memstats_other_sys_bytes gauge # TYPE go_memstats_other_sys_bytes gauge
# HELP go_memstats_stack_inuse_bytes Number of bytes in use by the stack allocator. # HELP go_memstats_stack_inuse_bytes Number of bytes obtained from system for stack allocator in non-CGO environments. Equals to /memory/classes/heap/stacks:bytes.
# TYPE go_memstats_stack_inuse_bytes gauge # TYPE go_memstats_stack_inuse_bytes gauge
# HELP go_memstats_stack_sys_bytes Number of bytes obtained from system for stack allocator. # HELP go_memstats_stack_sys_bytes Number of bytes obtained from system for stack allocator. Equals to /memory/classes/heap/stacks:bytes + /memory/classes/os-stacks:bytes.
# TYPE go_memstats_stack_sys_bytes gauge # TYPE go_memstats_stack_sys_bytes gauge
# HELP go_memstats_sys_bytes Number of bytes obtained from system. # HELP go_memstats_sys_bytes Number of bytes obtained from system. Equals to /memory/classes/total:byte.
# TYPE go_memstats_sys_bytes gauge # TYPE go_memstats_sys_bytes gauge
# HELP go_sched_gomaxprocs_threads The current runtime.GOMAXPROCS setting, or the number of operating system threads that can execute user-level Go code simultaneously. Sourced from /sched/gomaxprocs:threads
# TYPE go_sched_gomaxprocs_threads gauge
# HELP go_threads Number of OS threads created. # HELP go_threads Number of OS threads created.
# TYPE go_threads gauge # TYPE go_threads gauge
# HELP node_arp_entries ARP entries by device # HELP node_arp_entries ARP entries by device
@ -4589,6 +4593,10 @@ node_zoneinfo_spanned_pages{node="0",zone="Normal"} 7.806976e+06
# TYPE process_cpu_seconds_total counter # TYPE process_cpu_seconds_total counter
# HELP process_max_fds Maximum number of open file descriptors. # HELP process_max_fds Maximum number of open file descriptors.
# TYPE process_max_fds gauge # TYPE process_max_fds gauge
# HELP process_network_receive_bytes_total Number of bytes received by the process over the network.
# TYPE process_network_receive_bytes_total counter
# HELP process_network_transmit_bytes_total Number of bytes sent by the process over the network.
# TYPE process_network_transmit_bytes_total counter
# HELP process_open_fds Number of open file descriptors. # HELP process_open_fds Number of open file descriptors.
# TYPE process_open_fds gauge # TYPE process_open_fds gauge
# HELP process_resident_memory_bytes Resident memory size in bytes. # HELP process_resident_memory_bytes Resident memory size in bytes.

View file

@ -1,55 +1,59 @@
# HELP go_gc_duration_seconds A summary of the pause duration of garbage collection cycles. # HELP go_gc_duration_seconds A summary of the wall-time pause (stop-the-world) duration in garbage collection cycles.
# TYPE go_gc_duration_seconds summary # TYPE go_gc_duration_seconds summary
# HELP go_gc_gogc_percent Heap size target percentage configured by the user, otherwise 100. This value is set by the GOGC environment variable, and the runtime/debug.SetGCPercent function. Sourced from /gc/gogc:percent
# TYPE go_gc_gogc_percent gauge
# HELP go_gc_gomemlimit_bytes Go runtime memory limit configured by the user, otherwise math.MaxInt64. This value is set by the GOMEMLIMIT environment variable, and the runtime/debug.SetMemoryLimit function. Sourced from /gc/gomemlimit:bytes
# TYPE go_gc_gomemlimit_bytes gauge
# HELP go_goroutines Number of goroutines that currently exist. # HELP go_goroutines Number of goroutines that currently exist.
# TYPE go_goroutines gauge # TYPE go_goroutines gauge
# HELP go_info Information about the Go environment. # HELP go_info Information about the Go environment.
# TYPE go_info gauge # TYPE go_info gauge
# HELP go_memstats_alloc_bytes Number of bytes allocated and still in use. # HELP go_memstats_alloc_bytes Number of bytes allocated in heap and currently in use. Equals to /memory/classes/heap/objects:bytes.
# TYPE go_memstats_alloc_bytes gauge # TYPE go_memstats_alloc_bytes gauge
# HELP go_memstats_alloc_bytes_total Total number of bytes allocated, even if freed. # HELP go_memstats_alloc_bytes_total Total number of bytes allocated in heap until now, even if released already. Equals to /gc/heap/allocs:bytes.
# TYPE go_memstats_alloc_bytes_total counter # TYPE go_memstats_alloc_bytes_total counter
# HELP go_memstats_buck_hash_sys_bytes Number of bytes used by the profiling bucket hash table. # HELP go_memstats_buck_hash_sys_bytes Number of bytes used by the profiling bucket hash table. Equals to /memory/classes/profiling/buckets:bytes.
# TYPE go_memstats_buck_hash_sys_bytes gauge # TYPE go_memstats_buck_hash_sys_bytes gauge
# HELP go_memstats_frees_total Total number of frees. # HELP go_memstats_frees_total Total number of heap objects frees. Equals to /gc/heap/frees:objects + /gc/heap/tiny/allocs:objects.
# TYPE go_memstats_frees_total counter # TYPE go_memstats_frees_total counter
# HELP go_memstats_gc_sys_bytes Number of bytes used for garbage collection system metadata. # HELP go_memstats_gc_sys_bytes Number of bytes used for garbage collection system metadata. Equals to /memory/classes/metadata/other:bytes.
# TYPE go_memstats_gc_sys_bytes gauge # TYPE go_memstats_gc_sys_bytes gauge
# HELP go_memstats_heap_alloc_bytes Number of heap bytes allocated and still in use. # HELP go_memstats_heap_alloc_bytes Number of heap bytes allocated and currently in use, same as go_memstats_alloc_bytes. Equals to /memory/classes/heap/objects:bytes.
# TYPE go_memstats_heap_alloc_bytes gauge # TYPE go_memstats_heap_alloc_bytes gauge
# HELP go_memstats_heap_idle_bytes Number of heap bytes waiting to be used. # HELP go_memstats_heap_idle_bytes Number of heap bytes waiting to be used. Equals to /memory/classes/heap/released:bytes + /memory/classes/heap/free:bytes.
# TYPE go_memstats_heap_idle_bytes gauge # TYPE go_memstats_heap_idle_bytes gauge
# HELP go_memstats_heap_inuse_bytes Number of heap bytes that are in use. # HELP go_memstats_heap_inuse_bytes Number of heap bytes that are in use. Equals to /memory/classes/heap/objects:bytes + /memory/classes/heap/unused:bytes
# TYPE go_memstats_heap_inuse_bytes gauge # TYPE go_memstats_heap_inuse_bytes gauge
# HELP go_memstats_heap_objects Number of allocated objects. # HELP go_memstats_heap_objects Number of currently allocated objects. Equals to /gc/heap/objects:objects.
# TYPE go_memstats_heap_objects gauge # TYPE go_memstats_heap_objects gauge
# HELP go_memstats_heap_released_bytes Number of heap bytes released to OS. # HELP go_memstats_heap_released_bytes Number of heap bytes released to OS. Equals to /memory/classes/heap/released:bytes.
# TYPE go_memstats_heap_released_bytes gauge # TYPE go_memstats_heap_released_bytes gauge
# HELP go_memstats_heap_sys_bytes Number of heap bytes obtained from system. # HELP go_memstats_heap_sys_bytes Number of heap bytes obtained from system. Equals to /memory/classes/heap/objects:bytes + /memory/classes/heap/unused:bytes + /memory/classes/heap/released:bytes + /memory/classes/heap/free:bytes.
# TYPE go_memstats_heap_sys_bytes gauge # TYPE go_memstats_heap_sys_bytes gauge
# HELP go_memstats_last_gc_time_seconds Number of seconds since 1970 of last garbage collection. # HELP go_memstats_last_gc_time_seconds Number of seconds since 1970 of last garbage collection.
# TYPE go_memstats_last_gc_time_seconds gauge # TYPE go_memstats_last_gc_time_seconds gauge
# HELP go_memstats_lookups_total Total number of pointer lookups. # HELP go_memstats_mallocs_total Total number of heap objects allocated, both live and gc-ed. Semantically a counter version for go_memstats_heap_objects gauge. Equals to /gc/heap/allocs:objects + /gc/heap/tiny/allocs:objects.
# TYPE go_memstats_lookups_total counter
# HELP go_memstats_mallocs_total Total number of mallocs.
# TYPE go_memstats_mallocs_total counter # TYPE go_memstats_mallocs_total counter
# HELP go_memstats_mcache_inuse_bytes Number of bytes in use by mcache structures. # HELP go_memstats_mcache_inuse_bytes Number of bytes in use by mcache structures. Equals to /memory/classes/metadata/mcache/inuse:bytes.
# TYPE go_memstats_mcache_inuse_bytes gauge # TYPE go_memstats_mcache_inuse_bytes gauge
# HELP go_memstats_mcache_sys_bytes Number of bytes used for mcache structures obtained from system. # HELP go_memstats_mcache_sys_bytes Number of bytes used for mcache structures obtained from system. Equals to /memory/classes/metadata/mcache/inuse:bytes + /memory/classes/metadata/mcache/free:bytes.
# TYPE go_memstats_mcache_sys_bytes gauge # TYPE go_memstats_mcache_sys_bytes gauge
# HELP go_memstats_mspan_inuse_bytes Number of bytes in use by mspan structures. # HELP go_memstats_mspan_inuse_bytes Number of bytes in use by mspan structures. Equals to /memory/classes/metadata/mspan/inuse:bytes.
# TYPE go_memstats_mspan_inuse_bytes gauge # TYPE go_memstats_mspan_inuse_bytes gauge
# HELP go_memstats_mspan_sys_bytes Number of bytes used for mspan structures obtained from system. # HELP go_memstats_mspan_sys_bytes Number of bytes used for mspan structures obtained from system. Equals to /memory/classes/metadata/mspan/inuse:bytes + /memory/classes/metadata/mspan/free:bytes.
# TYPE go_memstats_mspan_sys_bytes gauge # TYPE go_memstats_mspan_sys_bytes gauge
# HELP go_memstats_next_gc_bytes Number of heap bytes when next garbage collection will take place. # HELP go_memstats_next_gc_bytes Number of heap bytes when next garbage collection will take place. Equals to /gc/heap/goal:bytes.
# TYPE go_memstats_next_gc_bytes gauge # TYPE go_memstats_next_gc_bytes gauge
# HELP go_memstats_other_sys_bytes Number of bytes used for other system allocations. # HELP go_memstats_other_sys_bytes Number of bytes used for other system allocations. Equals to /memory/classes/other:bytes.
# TYPE go_memstats_other_sys_bytes gauge # TYPE go_memstats_other_sys_bytes gauge
# HELP go_memstats_stack_inuse_bytes Number of bytes in use by the stack allocator. # HELP go_memstats_stack_inuse_bytes Number of bytes obtained from system for stack allocator in non-CGO environments. Equals to /memory/classes/heap/stacks:bytes.
# TYPE go_memstats_stack_inuse_bytes gauge # TYPE go_memstats_stack_inuse_bytes gauge
# HELP go_memstats_stack_sys_bytes Number of bytes obtained from system for stack allocator. # HELP go_memstats_stack_sys_bytes Number of bytes obtained from system for stack allocator. Equals to /memory/classes/heap/stacks:bytes + /memory/classes/os-stacks:bytes.
# TYPE go_memstats_stack_sys_bytes gauge # TYPE go_memstats_stack_sys_bytes gauge
# HELP go_memstats_sys_bytes Number of bytes obtained from system. # HELP go_memstats_sys_bytes Number of bytes obtained from system. Equals to /memory/classes/total:byte.
# TYPE go_memstats_sys_bytes gauge # TYPE go_memstats_sys_bytes gauge
# HELP go_sched_gomaxprocs_threads The current runtime.GOMAXPROCS setting, or the number of operating system threads that can execute user-level Go code simultaneously. Sourced from /sched/gomaxprocs:threads
# TYPE go_sched_gomaxprocs_threads gauge
# HELP go_threads Number of OS threads created. # HELP go_threads Number of OS threads created.
# TYPE go_threads gauge # TYPE go_threads gauge
# HELP node_arp_entries ARP entries by device # HELP node_arp_entries ARP entries by device
@ -4611,6 +4615,10 @@ node_zoneinfo_spanned_pages{node="0",zone="Normal"} 7.806976e+06
# TYPE process_cpu_seconds_total counter # TYPE process_cpu_seconds_total counter
# HELP process_max_fds Maximum number of open file descriptors. # HELP process_max_fds Maximum number of open file descriptors.
# TYPE process_max_fds gauge # TYPE process_max_fds gauge
# HELP process_network_receive_bytes_total Number of bytes received by the process over the network.
# TYPE process_network_receive_bytes_total counter
# HELP process_network_transmit_bytes_total Number of bytes sent by the process over the network.
# TYPE process_network_transmit_bytes_total counter
# HELP process_open_fds Number of open file descriptors. # HELP process_open_fds Number of open file descriptors.
# TYPE process_open_fds gauge # TYPE process_open_fds gauge
# HELP process_resident_memory_bytes Resident memory size in bytes. # HELP process_resident_memory_bytes Resident memory size in bytes.

View file

@ -18,6 +18,7 @@ package collector
import ( import (
"errors" "errors"
"log/slog"
"os" "os"
"path/filepath" "path/filepath"
"regexp" "regexp"
@ -25,8 +26,6 @@ import (
"strings" "strings"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
@ -55,12 +54,12 @@ func init() {
type hwMonCollector struct { type hwMonCollector struct {
deviceFilter deviceFilter deviceFilter deviceFilter
sensorFilter deviceFilter sensorFilter deviceFilter
logger log.Logger logger *slog.Logger
} }
// NewHwMonCollector returns a new Collector exposing /sys/class/hwmon stats // NewHwMonCollector returns a new Collector exposing /sys/class/hwmon stats
// (similar to lm-sensors). // (similar to lm-sensors).
func NewHwMonCollector(logger log.Logger) (Collector, error) { func NewHwMonCollector(logger *slog.Logger) (Collector, error) {
return &hwMonCollector{ return &hwMonCollector{
logger: logger, logger: logger,
@ -168,7 +167,7 @@ func (c *hwMonCollector) updateHwmon(ch chan<- prometheus.Metric, dir string) er
} }
if c.deviceFilter.ignored(hwmonName) { if c.deviceFilter.ignored(hwmonName) {
level.Debug(c.logger).Log("msg", "ignoring hwmon chip", "chip", hwmonName) c.logger.Debug("ignoring hwmon chip", "chip", hwmonName)
return nil return nil
} }
@ -211,7 +210,7 @@ func (c *hwMonCollector) updateHwmon(ch chan<- prometheus.Metric, dir string) er
// sensors on specific devices. For example, to exclude the sensor "temp3" on // sensors on specific devices. For example, to exclude the sensor "temp3" on
// the device "platform_coretemp_0", use "platform_coretemp_0;temp3" // the device "platform_coretemp_0", use "platform_coretemp_0;temp3"
if c.sensorFilter.ignored(hwmonName + ";" + sensor) { if c.sensorFilter.ignored(hwmonName + ";" + sensor) {
level.Debug(c.logger).Log("msg", "ignoring sensor", "sensor", sensor) c.logger.Debug("ignoring sensor", "sensor", sensor)
continue continue
} }
@ -450,7 +449,7 @@ func (c *hwMonCollector) Update(ch chan<- prometheus.Metric) error {
hwmonFiles, err := os.ReadDir(hwmonPathName) hwmonFiles, err := os.ReadDir(hwmonPathName)
if err != nil { if err != nil {
if errors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {
level.Debug(c.logger).Log("msg", "hwmon collector metrics are not available for this system") c.logger.Debug("hwmon collector metrics are not available for this system")
return ErrNoData return ErrNoData
} }

View file

@ -19,11 +19,10 @@ package collector
import ( import (
"errors" "errors"
"fmt" "fmt"
"log/slog"
"os" "os"
"strconv" "strconv"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/procfs/sysfs" "github.com/prometheus/procfs/sysfs"
) )
@ -31,7 +30,7 @@ import (
type infinibandCollector struct { type infinibandCollector struct {
fs sysfs.FS fs sysfs.FS
metricDescs map[string]*prometheus.Desc metricDescs map[string]*prometheus.Desc
logger log.Logger logger *slog.Logger
subsystem string subsystem string
} }
@ -40,7 +39,7 @@ func init() {
} }
// NewInfiniBandCollector returns a new Collector exposing InfiniBand stats. // NewInfiniBandCollector returns a new Collector exposing InfiniBand stats.
func NewInfiniBandCollector(logger log.Logger) (Collector, error) { func NewInfiniBandCollector(logger *slog.Logger) (Collector, error) {
var i infinibandCollector var i infinibandCollector
var err error var err error
@ -116,7 +115,7 @@ func (c *infinibandCollector) Update(ch chan<- prometheus.Metric) error {
devices, err := c.fs.InfiniBandClass() devices, err := c.fs.InfiniBandClass()
if err != nil { if err != nil {
if errors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {
level.Debug(c.logger).Log("msg", "infiniband statistics not found, skipping") c.logger.Debug("infiniband statistics not found, skipping")
return ErrNoData return ErrNoData
} }
return fmt.Errorf("error obtaining InfiniBand class info: %w", err) return fmt.Errorf("error obtaining InfiniBand class info: %w", err)

View file

@ -19,13 +19,13 @@ package collector
import ( import (
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"log/slog"
) )
type interruptsCollector struct { type interruptsCollector struct {
desc typedDesc desc typedDesc
logger log.Logger logger *slog.Logger
nameFilter deviceFilter nameFilter deviceFilter
includeZeros bool includeZeros bool
} }
@ -41,7 +41,7 @@ var (
) )
// NewInterruptsCollector returns a new Collector exposing interrupts stats. // NewInterruptsCollector returns a new Collector exposing interrupts stats.
func NewInterruptsCollector(logger log.Logger) (Collector, error) { func NewInterruptsCollector(logger *slog.Logger) (Collector, error) {
return &interruptsCollector{ return &interruptsCollector{
desc: typedDesc{prometheus.NewDesc( desc: typedDesc{prometheus.NewDesc(
namespace+"_interrupts_total", namespace+"_interrupts_total",

View file

@ -25,7 +25,6 @@ import (
"strconv" "strconv"
"strings" "strings"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -42,7 +41,7 @@ func (c *interruptsCollector) Update(ch chan<- prometheus.Metric) (err error) {
for cpuNo, value := range interrupt.values { for cpuNo, value := range interrupt.values {
filterName := name + ";" + interrupt.info + ";" + interrupt.devices filterName := name + ";" + interrupt.info + ";" + interrupt.devices
if c.nameFilter.ignored(filterName) { if c.nameFilter.ignored(filterName) {
level.Debug(c.logger).Log("msg", "ignoring interrupt name", "filter_name", filterName) c.logger.Debug("ignoring interrupt name", "filter_name", filterName)
continue continue
} }
fv, err := strconv.ParseFloat(value, 64) fv, err := strconv.ParseFloat(value, 64)
@ -50,7 +49,7 @@ func (c *interruptsCollector) Update(ch chan<- prometheus.Metric) (err error) {
return fmt.Errorf("invalid value %s in interrupts: %w", value, err) return fmt.Errorf("invalid value %s in interrupts: %w", value, err)
} }
if !c.includeZeros && fv == 0.0 { if !c.includeZeros && fv == 0.0 {
level.Debug(c.logger).Log("msg", "ignoring interrupt with zero value", "filter_name", filterName, "cpu", cpuNo) c.logger.Debug("ignoring interrupt with zero value", "filter_name", filterName, "cpu", cpuNo)
continue continue
} }
ch <- c.desc.mustNewConstMetric(fv, strconv.Itoa(cpuNo), name, interrupt.info, interrupt.devices) ch <- c.desc.mustNewConstMetric(fv, strconv.Itoa(cpuNo), name, interrupt.info, interrupt.devices)

View file

@ -20,7 +20,6 @@ import (
"fmt" "fmt"
"strconv" "strconv"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -110,11 +109,11 @@ func (c *interruptsCollector) Update(ch chan<- prometheus.Metric) error {
interruptType := fmt.Sprintf("%d", interrupt.vector) interruptType := fmt.Sprintf("%d", interrupt.vector)
filterName := interruptType + ";" + dev filterName := interruptType + ";" + dev
if c.nameFilter.ignored(filterName) { if c.nameFilter.ignored(filterName) {
level.Debug(c.logger).Log("msg", "ignoring interrupt name", "filter_name", filterName) c.logger.Debug("ignoring interrupt name", "filter_name", filterName)
continue continue
} }
if !c.includeZeros && value == 0.0 { if !c.includeZeros && value == 0.0 {
level.Debug(c.logger).Log("msg", "ignoring interrupt with zero value", "filter_name", filterName, "cpu", cpuNo) c.logger.Debug("ignoring interrupt with zero value", "filter_name", filterName, "cpu", cpuNo)
continue continue
} }
ch <- c.desc.mustNewConstMetric( ch <- c.desc.mustNewConstMetric(

View file

@ -21,7 +21,6 @@ import (
"strconv" "strconv"
"unsafe" "unsafe"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
@ -81,11 +80,11 @@ func (c *interruptsCollector) Update(ch chan<- prometheus.Metric) error {
interruptType := fmt.Sprintf("%d", interrupt.vector) interruptType := fmt.Sprintf("%d", interrupt.vector)
filterName := interruptType + ";" + dev filterName := interruptType + ";" + dev
if c.nameFilter.ignored(filterName) { if c.nameFilter.ignored(filterName) {
level.Debug(c.logger).Log("msg", "ignoring interrupt name", "filter_name", filterName) c.logger.Debug("ignoring interrupt name", "filter_name", filterName)
continue continue
} }
if !c.includeZeros && value == 0.0 { if !c.includeZeros && value == 0.0 {
level.Debug(c.logger).Log("msg", "ignoring interrupt with zero value", "filter_name", filterName, "cpu", cpuNo) c.logger.Debug("ignoring interrupt with zero value", "filter_name", filterName, "cpu", cpuNo)
continue continue
} }
ch <- c.desc.mustNewConstMetric( ch <- c.desc.mustNewConstMetric(

View file

@ -19,14 +19,13 @@ package collector
import ( import (
"errors" "errors"
"fmt" "fmt"
"log/slog"
"os" "os"
"sort" "sort"
"strconv" "strconv"
"strings" "strings"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/procfs" "github.com/prometheus/procfs"
) )
@ -37,7 +36,7 @@ type ipvsCollector struct {
backendLabels []string backendLabels []string
backendConnectionsActive, backendConnectionsInact, backendWeight typedDesc backendConnectionsActive, backendConnectionsInact, backendWeight typedDesc
connections, incomingPackets, outgoingPackets, incomingBytes, outgoingBytes typedDesc connections, incomingPackets, outgoingPackets, incomingBytes, outgoingBytes typedDesc
logger log.Logger logger *slog.Logger
} }
type ipvsBackendStatus struct { type ipvsBackendStatus struct {
@ -73,11 +72,11 @@ func init() {
// NewIPVSCollector sets up a new collector for IPVS metrics. It accepts the // NewIPVSCollector sets up a new collector for IPVS metrics. It accepts the
// "procfs" config parameter to override the default proc location (/proc). // "procfs" config parameter to override the default proc location (/proc).
func NewIPVSCollector(logger log.Logger) (Collector, error) { func NewIPVSCollector(logger *slog.Logger) (Collector, error) {
return newIPVSCollector(logger) return newIPVSCollector(logger)
} }
func newIPVSCollector(logger log.Logger) (*ipvsCollector, error) { func newIPVSCollector(logger *slog.Logger) (*ipvsCollector, error) {
var ( var (
c ipvsCollector c ipvsCollector
err error err error
@ -143,7 +142,7 @@ func (c *ipvsCollector) Update(ch chan<- prometheus.Metric) error {
if err != nil { if err != nil {
// Cannot access ipvs metrics, report no error. // Cannot access ipvs metrics, report no error.
if errors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {
level.Debug(c.logger).Log("msg", "ipvs collector metrics are not available for this system") c.logger.Debug("ipvs collector metrics are not available for this system")
return ErrNoData return ErrNoData
} }
return fmt.Errorf("could not get IPVS stats: %w", err) return fmt.Errorf("could not get IPVS stats: %w", err)

View file

@ -19,14 +19,14 @@ package collector
import ( import (
"errors" "errors"
"fmt" "fmt"
"io"
"log/slog"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"os" "os"
"strings" "strings"
"testing" "testing"
"github.com/go-kit/log"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp" "github.com/prometheus/client_golang/prometheus/promhttp"
@ -114,7 +114,7 @@ func TestIPVSCollector(t *testing.T) {
if _, err := kingpin.CommandLine.Parse(args); err != nil { if _, err := kingpin.CommandLine.Parse(args); err != nil {
t.Fatal(err) t.Fatal(err)
} }
collector, err := newIPVSCollector(log.NewNopLogger()) collector, err := newIPVSCollector(slog.New(slog.NewTextHandler(io.Discard, nil)))
if err != nil { if err != nil {
if test.err == nil { if test.err == nil {
t.Fatal(err) t.Fatal(err)
@ -182,7 +182,7 @@ func TestIPVSCollectorResponse(t *testing.T) {
if _, err := kingpin.CommandLine.Parse(args); err != nil { if _, err := kingpin.CommandLine.Parse(args); err != nil {
t.Fatal(err) t.Fatal(err)
} }
collector, err := NewIPVSCollector(log.NewNopLogger()) collector, err := NewIPVSCollector(slog.New(slog.NewTextHandler(io.Discard, nil)))
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View file

@ -18,9 +18,9 @@ package collector
import ( import (
"fmt" "fmt"
"log/slog"
"path/filepath" "path/filepath"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -31,7 +31,7 @@ var (
type ksmdCollector struct { type ksmdCollector struct {
metricDescs map[string]*prometheus.Desc metricDescs map[string]*prometheus.Desc
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -50,7 +50,7 @@ func getCanonicalMetricName(filename string) string {
} }
// NewKsmdCollector returns a new Collector exposing kernel/system statistics. // NewKsmdCollector returns a new Collector exposing kernel/system statistics.
func NewKsmdCollector(logger log.Logger) (Collector, error) { func NewKsmdCollector(logger *slog.Logger) (Collector, error) {
subsystem := "ksmd" subsystem := "ksmd"
descs := make(map[string]*prometheus.Desc) descs := make(map[string]*prometheus.Desc)

View file

@ -18,22 +18,22 @@ package collector
import ( import (
"fmt" "fmt"
"log/slog"
"strconv" "strconv"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/procfs" "github.com/prometheus/procfs"
) )
type lnstatCollector struct { type lnstatCollector struct {
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
registerCollector("lnstat", defaultDisabled, NewLnstatCollector) registerCollector("lnstat", defaultDisabled, NewLnstatCollector)
} }
func NewLnstatCollector(logger log.Logger) (Collector, error) { func NewLnstatCollector(logger *slog.Logger) (Collector, error) {
return &lnstatCollector{logger}, nil return &lnstatCollector{logger}, nil
} }

View file

@ -19,15 +19,14 @@ package collector
import ( import (
"fmt" "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"
) )
type loadavgCollector struct { type loadavgCollector struct {
metric []typedDesc metric []typedDesc
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -35,7 +34,7 @@ func init() {
} }
// NewLoadavgCollector returns a new Collector exposing load average stats. // NewLoadavgCollector returns a new Collector exposing load average stats.
func NewLoadavgCollector(logger log.Logger) (Collector, error) { func NewLoadavgCollector(logger *slog.Logger) (Collector, error) {
return &loadavgCollector{ return &loadavgCollector{
metric: []typedDesc{ metric: []typedDesc{
{prometheus.NewDesc(namespace+"_load1", "1m load average.", nil, nil), prometheus.GaugeValue}, {prometheus.NewDesc(namespace+"_load1", "1m load average.", nil, nil), prometheus.GaugeValue},
@ -52,7 +51,7 @@ func (c *loadavgCollector) Update(ch chan<- prometheus.Metric) error {
return fmt.Errorf("couldn't get load: %w", err) return fmt.Errorf("couldn't get load: %w", err)
} }
for i, load := range loads { for i, load := range loads {
level.Debug(c.logger).Log("msg", "return load", "index", i, "load", load) c.logger.Debug("return load", "index", i, "load", load)
ch <- c.metric[i].mustNewConstMetric(load) ch <- c.metric[i].mustNewConstMetric(load)
} }
return err return err

View file

@ -18,10 +18,10 @@ package collector
import ( import (
"fmt" "fmt"
"log/slog"
"os" "os"
"strconv" "strconv"
"github.com/go-kit/log"
"github.com/godbus/dbus/v5" "github.com/godbus/dbus/v5"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -46,7 +46,7 @@ var (
) )
type logindCollector struct { type logindCollector struct {
logger log.Logger logger *slog.Logger
} }
type logindDbus struct { type logindDbus struct {
@ -86,7 +86,7 @@ func init() {
} }
// NewLogindCollector returns a new Collector exposing logind statistics. // NewLogindCollector returns a new Collector exposing logind statistics.
func NewLogindCollector(logger log.Logger) (Collector, error) { func NewLogindCollector(logger *slog.Logger) (Collector, error) {
return &logindCollector{logger}, nil return &logindCollector{logger}, nil
} }

View file

@ -19,16 +19,15 @@ package collector
import ( import (
"errors" "errors"
"fmt" "fmt"
"log/slog"
"os" "os"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/procfs" "github.com/prometheus/procfs"
) )
type mdadmCollector struct { type mdadmCollector struct {
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -36,7 +35,7 @@ func init() {
} }
// NewMdadmCollector returns a new Collector exposing raid statistics. // NewMdadmCollector returns a new Collector exposing raid statistics.
func NewMdadmCollector(logger log.Logger) (Collector, error) { func NewMdadmCollector(logger *slog.Logger) (Collector, error) {
return &mdadmCollector{logger}, nil return &mdadmCollector{logger}, nil
} }
@ -112,7 +111,7 @@ func (c *mdadmCollector) Update(ch chan<- prometheus.Metric) error {
if err != nil { if err != nil {
if errors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {
level.Debug(c.logger).Log("msg", "Not collecting mdstat, file does not exist", "file", *procPath) c.logger.Debug("Not collecting mdstat, file does not exist", "file", *procPath)
return ErrNoData return ErrNoData
} }
@ -120,7 +119,7 @@ func (c *mdadmCollector) Update(ch chan<- prometheus.Metric) error {
} }
for _, mdStat := range mdStats { for _, mdStat := range mdStats {
level.Debug(c.logger).Log("msg", "collecting metrics for device", "device", mdStat.Name) c.logger.Debug("collecting metrics for device", "device", mdStat.Name)
stateVals := make(map[string]float64) stateVals := make(map[string]float64)
stateVals[mdStat.ActivityState] = 1 stateVals[mdStat.ActivityState] = 1

View file

@ -21,7 +21,6 @@ import (
"fmt" "fmt"
"strings" "strings"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -41,7 +40,7 @@ func (c *meminfoCollector) Update(ch chan<- prometheus.Metric) error {
if err != nil { if err != nil {
return fmt.Errorf("couldn't get meminfo: %w", err) return fmt.Errorf("couldn't get meminfo: %w", err)
} }
level.Debug(c.logger).Log("msg", "Set node_mem", "memInfo", fmt.Sprintf("%v", memInfo)) c.logger.Debug("Set node_mem", "memInfo", fmt.Sprintf("%v", memInfo))
for k, v := range memInfo { for k, v := range memInfo {
if strings.HasSuffix(k, "_total") { if strings.HasSuffix(k, "_total") {
metricType = prometheus.CounterValue metricType = prometheus.CounterValue

View file

@ -24,18 +24,18 @@ import "C"
import ( import (
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"log/slog"
"unsafe" "unsafe"
"github.com/go-kit/log"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
type meminfoCollector struct { type meminfoCollector struct {
logger log.Logger logger *slog.Logger
} }
// NewMeminfoCollector returns a new Collector exposing memory stats. // NewMeminfoCollector returns a new Collector exposing memory stats.
func NewMeminfoCollector(logger log.Logger) (Collector, error) { func NewMeminfoCollector(logger *slog.Logger) (Collector, error) {
return &meminfoCollector{ return &meminfoCollector{
logger: logger, logger: logger,
}, nil }, nil

View file

@ -18,18 +18,18 @@ package collector
import ( import (
"fmt" "fmt"
"log/slog"
"github.com/go-kit/log"
"github.com/prometheus/procfs" "github.com/prometheus/procfs"
) )
type meminfoCollector struct { type meminfoCollector struct {
fs procfs.FS fs procfs.FS
logger log.Logger logger *slog.Logger
} }
// NewMeminfoCollector returns a new Collector exposing memory stats. // NewMeminfoCollector returns a new Collector exposing memory stats.
func NewMeminfoCollector(logger log.Logger) (Collector, error) { func NewMeminfoCollector(logger *slog.Logger) (Collector, error) {
fs, err := procfs.NewFS(*procPath) fs, err := procfs.NewFS(*procPath)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to open procfs: %w", err) return nil, fmt.Errorf("failed to open procfs: %w", err)

View file

@ -17,15 +17,14 @@
package collector package collector
import ( import (
"os" "io"
"log/slog"
"testing" "testing"
"github.com/go-kit/log"
) )
func TestMemInfo(t *testing.T) { func TestMemInfo(t *testing.T) {
*procPath = "fixtures/proc" *procPath = "fixtures/proc"
logger := log.NewLogfmtLogger(os.Stderr) logger := slog.New(slog.NewTextHandler(io.Discard, nil))
collector, err := NewMeminfoCollector(logger) collector, err := NewMeminfoCollector(logger)
if err != nil { if err != nil {

View file

@ -17,16 +17,16 @@
package collector package collector
import ( import (
"github.com/go-kit/log"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
"log/slog"
) )
type meminfoCollector struct { type meminfoCollector struct {
logger log.Logger logger *slog.Logger
} }
// NewMeminfoCollector returns a new Collector exposing memory stats. // NewMeminfoCollector returns a new Collector exposing memory stats.
func NewMeminfoCollector(logger log.Logger) (Collector, error) { func NewMeminfoCollector(logger *slog.Logger) (Collector, error) {
return &meminfoCollector{ return &meminfoCollector{
logger: logger, logger: logger,
}, nil }, nil

View file

@ -20,13 +20,13 @@ import (
"bufio" "bufio"
"fmt" "fmt"
"io" "io"
"log/slog"
"os" "os"
"path/filepath" "path/filepath"
"regexp" "regexp"
"strconv" "strconv"
"strings" "strings"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -45,7 +45,7 @@ type meminfoMetric struct {
type meminfoNumaCollector struct { type meminfoNumaCollector struct {
metricDescs map[string]*prometheus.Desc metricDescs map[string]*prometheus.Desc
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -53,7 +53,7 @@ func init() {
} }
// NewMeminfoNumaCollector returns a new Collector exposing memory stats. // NewMeminfoNumaCollector returns a new Collector exposing memory stats.
func NewMeminfoNumaCollector(logger log.Logger) (Collector, error) { func NewMeminfoNumaCollector(logger *slog.Logger) (Collector, error) {
return &meminfoNumaCollector{ return &meminfoNumaCollector{
metricDescs: map[string]*prometheus.Desc{}, metricDescs: map[string]*prometheus.Desc{},
logger: logger, logger: logger,

View file

@ -18,8 +18,7 @@ package collector
import ( import (
"fmt" "fmt"
"log/slog"
"github.com/go-kit/log"
) )
/* /*
@ -56,11 +55,11 @@ sysctl_bcstats(struct bcachestats *bcstats)
import "C" import "C"
type meminfoCollector struct { type meminfoCollector struct {
logger log.Logger logger *slog.Logger
} }
// NewMeminfoCollector returns a new Collector exposing memory stats. // NewMeminfoCollector returns a new Collector exposing memory stats.
func NewMeminfoCollector(logger log.Logger) (Collector, error) { func NewMeminfoCollector(logger *slog.Logger) (Collector, error) {
return &meminfoCollector{ return &meminfoCollector{
logger: logger, logger: logger,
}, nil }, nil

View file

@ -17,9 +17,9 @@
package collector package collector
import ( import (
"log/slog"
"unsafe" "unsafe"
"github.com/go-kit/log"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
@ -51,11 +51,11 @@ type bcachestats struct {
} }
type meminfoCollector struct { type meminfoCollector struct {
logger log.Logger logger *slog.Logger
} }
// NewMeminfoCollector returns a new Collector exposing memory stats. // NewMeminfoCollector returns a new Collector exposing memory stats.
func NewMeminfoCollector(logger log.Logger) (Collector, error) { func NewMeminfoCollector(logger *slog.Logger) (Collector, error) {
return &meminfoCollector{ return &meminfoCollector{
logger: logger, logger: logger,
}, nil }, nil

View file

@ -19,8 +19,8 @@ package collector
import ( import (
"fmt" "fmt"
"log/slog"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
@ -33,7 +33,7 @@ type memoryCollector struct {
pageSize uint64 pageSize uint64
sysctls []bsdSysctl sysctls []bsdSysctl
kvm kvm kvm kvm
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -41,7 +41,7 @@ func init() {
} }
// NewMemoryCollector returns a new Collector exposing memory stats. // NewMemoryCollector returns a new Collector exposing memory stats.
func NewMemoryCollector(logger log.Logger) (Collector, error) { func NewMemoryCollector(logger *slog.Logger) (Collector, error) {
tmp32, err := unix.SysctlUint32("vm.stats.vm.v_page_size") tmp32, err := unix.SysctlUint32("vm.stats.vm.v_page_size")
if err != nil { if err != nil {
return nil, fmt.Errorf("sysctl(vm.stats.vm.v_page_size) failed: %w", err) return nil, fmt.Errorf("sysctl(vm.stats.vm.v_page_size) failed: %w", err)

View file

@ -18,9 +18,8 @@ package collector
import ( import (
"fmt" "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"
"github.com/prometheus/procfs" "github.com/prometheus/procfs"
) )
@ -96,7 +95,7 @@ type mountStatsCollector struct {
proc procfs.Proc proc procfs.Proc
logger log.Logger logger *slog.Logger
} }
// used to uniquely identify an NFS mount to prevent duplicates // used to uniquely identify an NFS mount to prevent duplicates
@ -111,7 +110,7 @@ func init() {
} }
// NewMountStatsCollector returns a new Collector exposing NFS statistics. // NewMountStatsCollector returns a new Collector exposing NFS statistics.
func NewMountStatsCollector(logger log.Logger) (Collector, error) { func NewMountStatsCollector(logger *slog.Logger) (Collector, error) {
fs, err := procfs.NewFS(*procPath) fs, err := procfs.NewFS(*procPath)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to open procfs: %w", err) return nil, fmt.Errorf("failed to open procfs: %w", err)
@ -542,7 +541,7 @@ func (c *mountStatsCollector) Update(ch chan<- prometheus.Metric) error {
deviceIdentifier := nfsDeviceIdentifier{m.Device, stats.Transport[k].Protocol, mountAddress} deviceIdentifier := nfsDeviceIdentifier{m.Device, stats.Transport[k].Protocol, mountAddress}
i := deviceList[deviceIdentifier] i := deviceList[deviceIdentifier]
if i { if i {
level.Debug(c.logger).Log("msg", "Skipping duplicate device entry", "device", deviceIdentifier) c.logger.Debug("Skipping duplicate device entry", "device", deviceIdentifier)
break break
} }
deviceList[deviceIdentifier] = true deviceList[deviceIdentifier] = true

View file

@ -19,14 +19,13 @@ package collector
import ( import (
"errors" "errors"
"fmt" "fmt"
"log/slog"
"net" "net"
"os" "os"
"regexp" "regexp"
"sync" "sync"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/procfs/sysfs" "github.com/prometheus/procfs/sysfs"
) )
@ -43,7 +42,7 @@ type netClassCollector struct {
ignoredDevicesPattern *regexp.Regexp ignoredDevicesPattern *regexp.Regexp
metricDescs map[string]*prometheus.Desc metricDescs map[string]*prometheus.Desc
metricDescsMu sync.Mutex metricDescsMu sync.Mutex
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -51,7 +50,7 @@ func init() {
} }
// NewNetClassCollector returns a new Collector exposing network class stats. // NewNetClassCollector returns a new Collector exposing network class stats.
func NewNetClassCollector(logger log.Logger) (Collector, error) { func NewNetClassCollector(logger *slog.Logger) (Collector, error) {
fs, err := sysfs.NewFS(*sysPath) fs, err := sysfs.NewFS(*sysPath)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to open sysfs: %w", err) return nil, fmt.Errorf("failed to open sysfs: %w", err)
@ -77,7 +76,7 @@ func (c *netClassCollector) netClassSysfsUpdate(ch chan<- prometheus.Metric) err
netClass, err := c.getNetClassInfo() netClass, err := c.getNetClassInfo()
if err != nil { if err != nil {
if errors.Is(err, os.ErrNotExist) || errors.Is(err, os.ErrPermission) { if errors.Is(err, os.ErrNotExist) || errors.Is(err, os.ErrPermission) {
level.Debug(c.logger).Log("msg", "Could not read netclass file", "err", err) c.logger.Debug("Could not read netclass file", "err", err)
return ErrNoData return ErrNoData
} }
return fmt.Errorf("could not get net class info: %w", err) return fmt.Errorf("could not get net class info: %w", err)

View file

@ -23,7 +23,6 @@ import (
"path/filepath" "path/filepath"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log/level"
"github.com/jsimonetti/rtnetlink" "github.com/jsimonetti/rtnetlink"
"github.com/mdlayher/ethtool" "github.com/mdlayher/ethtool"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
@ -45,7 +44,7 @@ func (c *netClassCollector) netClassRTNLUpdate(ch chan<- prometheus.Metric) erro
if !errors.Is(errors.Unwrap(err), fs.ErrNotExist) { if !errors.Is(errors.Unwrap(err), fs.ErrNotExist) {
return fmt.Errorf("could not get link modes: %w", err) return fmt.Errorf("could not get link modes: %w", err)
} }
level.Info(c.logger).Log("msg", "ETHTOOL netlink interface unavailable, duplex and linkspeed are not scraped.") c.logger.Info("ETHTOOL netlink interface unavailable, duplex and linkspeed are not scraped.")
} else { } else {
for _, lm := range lms { for _, lm := range lms {
if c.ignoredDevicesPattern.MatchString(lm.Interface.Name) { if c.ignoredDevicesPattern.MatchString(lm.Interface.Name) {

View file

@ -19,9 +19,7 @@ package collector
import ( import (
"errors" "errors"
"log/slog"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
) )
/* /*
@ -34,7 +32,7 @@ import (
*/ */
import "C" import "C"
func getNetDevStats(filter *deviceFilter, logger log.Logger) (netDevStats, error) { func getNetDevStats(filter *deviceFilter, logger *slog.Logger) (netDevStats, error) {
netDev := netDevStats{} netDev := netDevStats{}
var ifap, ifa *C.struct_ifaddrs var ifap, ifa *C.struct_ifaddrs
@ -50,7 +48,7 @@ func getNetDevStats(filter *deviceFilter, logger log.Logger) (netDevStats, error
dev := C.GoString(ifa.ifa_name) dev := C.GoString(ifa.ifa_name)
if filter.ignored(dev) { if filter.ignored(dev) {
level.Debug(logger).Log("msg", "Ignoring device", "device", dev) logger.Debug("Ignoring device", "device", dev)
continue continue
} }

View file

@ -20,13 +20,12 @@ package collector
import ( import (
"errors" "errors"
"fmt" "fmt"
"log/slog"
"net" "net"
"strconv" "strconv"
"sync" "sync"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -44,7 +43,7 @@ type netDevCollector struct {
deviceFilter deviceFilter deviceFilter deviceFilter
metricDescsMutex sync.Mutex metricDescsMutex sync.Mutex
metricDescs map[string]*prometheus.Desc metricDescs map[string]*prometheus.Desc
logger log.Logger logger *slog.Logger
} }
type netDevStats map[string]map[string]uint64 type netDevStats map[string]map[string]uint64
@ -54,10 +53,10 @@ func init() {
} }
// NewNetDevCollector returns a new Collector exposing network device stats. // NewNetDevCollector returns a new Collector exposing network device stats.
func NewNetDevCollector(logger log.Logger) (Collector, error) { func NewNetDevCollector(logger *slog.Logger) (Collector, error) {
if *oldNetdevDeviceInclude != "" { if *oldNetdevDeviceInclude != "" {
if *netdevDeviceInclude == "" { if *netdevDeviceInclude == "" {
level.Warn(logger).Log("msg", "--collector.netdev.device-whitelist is DEPRECATED and will be removed in 2.0.0, use --collector.netdev.device-include") logger.Warn("--collector.netdev.device-whitelist is DEPRECATED and will be removed in 2.0.0, use --collector.netdev.device-include")
*netdevDeviceInclude = *oldNetdevDeviceInclude *netdevDeviceInclude = *oldNetdevDeviceInclude
} else { } else {
return nil, errors.New("--collector.netdev.device-whitelist and --collector.netdev.device-include are mutually exclusive") return nil, errors.New("--collector.netdev.device-whitelist and --collector.netdev.device-include are mutually exclusive")
@ -66,7 +65,7 @@ func NewNetDevCollector(logger log.Logger) (Collector, error) {
if *oldNetdevDeviceExclude != "" { if *oldNetdevDeviceExclude != "" {
if *netdevDeviceExclude == "" { if *netdevDeviceExclude == "" {
level.Warn(logger).Log("msg", "--collector.netdev.device-blacklist is DEPRECATED and will be removed in 2.0.0, use --collector.netdev.device-exclude") logger.Warn("--collector.netdev.device-blacklist is DEPRECATED and will be removed in 2.0.0, use --collector.netdev.device-exclude")
*netdevDeviceExclude = *oldNetdevDeviceExclude *netdevDeviceExclude = *oldNetdevDeviceExclude
} else { } else {
return nil, errors.New("--collector.netdev.device-blacklist and --collector.netdev.device-exclude are mutually exclusive") return nil, errors.New("--collector.netdev.device-blacklist and --collector.netdev.device-exclude are mutually exclusive")
@ -78,11 +77,11 @@ func NewNetDevCollector(logger log.Logger) (Collector, error) {
} }
if *netdevDeviceExclude != "" { if *netdevDeviceExclude != "" {
level.Info(logger).Log("msg", "Parsed flag --collector.netdev.device-exclude", "flag", *netdevDeviceExclude) logger.Info("Parsed flag --collector.netdev.device-exclude", "flag", *netdevDeviceExclude)
} }
if *netdevDeviceInclude != "" { if *netdevDeviceInclude != "" {
level.Info(logger).Log("msg", "Parsed Flag --collector.netdev.device-include", "flag", *netdevDeviceInclude) logger.Info("Parsed Flag --collector.netdev.device-include", "flag", *netdevDeviceInclude)
} }
return &netDevCollector{ return &netDevCollector{

View file

@ -20,14 +20,13 @@ import (
"bytes" "bytes"
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"log/slog"
"net" "net"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
func getNetDevStats(filter *deviceFilter, logger log.Logger) (netDevStats, error) { func getNetDevStats(filter *deviceFilter, logger *slog.Logger) (netDevStats, error) {
netDev := netDevStats{} netDev := netDevStats{}
ifs, err := net.Interfaces() ifs, err := net.Interfaces()
@ -37,13 +36,13 @@ func getNetDevStats(filter *deviceFilter, logger log.Logger) (netDevStats, error
for _, iface := range ifs { for _, iface := range ifs {
if filter.ignored(iface.Name) { if filter.ignored(iface.Name) {
level.Debug(logger).Log("msg", "Ignoring device", "device", iface.Name) logger.Debug("Ignoring device", "device", iface.Name)
continue continue
} }
ifaceData, err := getIfaceData(iface.Index) ifaceData, err := getIfaceData(iface.Index)
if err != nil { if err != nil {
level.Debug(logger).Log("msg", "failed to load data for interface", "device", iface.Name, "err", err) logger.Debug("failed to load data for interface", "device", iface.Name, "err", err)
continue continue
} }

View file

@ -18,10 +18,9 @@ package collector
import ( import (
"fmt" "fmt"
"log/slog"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/jsimonetti/rtnetlink" "github.com/jsimonetti/rtnetlink"
"github.com/prometheus/procfs" "github.com/prometheus/procfs"
) )
@ -30,14 +29,14 @@ var (
netDevNetlink = kingpin.Flag("collector.netdev.netlink", "Use netlink to gather stats instead of /proc/net/dev.").Default("true").Bool() netDevNetlink = kingpin.Flag("collector.netdev.netlink", "Use netlink to gather stats instead of /proc/net/dev.").Default("true").Bool()
) )
func getNetDevStats(filter *deviceFilter, logger log.Logger) (netDevStats, error) { func getNetDevStats(filter *deviceFilter, logger *slog.Logger) (netDevStats, error) {
if *netDevNetlink { if *netDevNetlink {
return netlinkStats(filter, logger) return netlinkStats(filter, logger)
} }
return procNetDevStats(filter, logger) return procNetDevStats(filter, logger)
} }
func netlinkStats(filter *deviceFilter, logger log.Logger) (netDevStats, error) { func netlinkStats(filter *deviceFilter, logger *slog.Logger) (netDevStats, error) {
conn, err := rtnetlink.Dial(nil) conn, err := rtnetlink.Dial(nil)
if err != nil { if err != nil {
return nil, err return nil, err
@ -52,12 +51,12 @@ func netlinkStats(filter *deviceFilter, logger log.Logger) (netDevStats, error)
return parseNetlinkStats(links, filter, logger), nil return parseNetlinkStats(links, filter, logger), nil
} }
func parseNetlinkStats(links []rtnetlink.LinkMessage, filter *deviceFilter, logger log.Logger) netDevStats { func parseNetlinkStats(links []rtnetlink.LinkMessage, filter *deviceFilter, logger *slog.Logger) netDevStats {
metrics := netDevStats{} metrics := netDevStats{}
for _, msg := range links { for _, msg := range links {
if msg.Attributes == nil { if msg.Attributes == nil {
level.Debug(logger).Log("msg", "No netlink attributes, skipping") logger.Debug("No netlink attributes, skipping")
continue continue
} }
name := msg.Attributes.Name name := msg.Attributes.Name
@ -93,13 +92,13 @@ func parseNetlinkStats(links []rtnetlink.LinkMessage, filter *deviceFilter, logg
} }
if filter.ignored(name) { if filter.ignored(name) {
level.Debug(logger).Log("msg", "Ignoring device", "device", name) logger.Debug("Ignoring device", "device", name)
continue continue
} }
// Make sure we don't panic when accessing `stats` attributes below. // Make sure we don't panic when accessing `stats` attributes below.
if stats == nil { if stats == nil {
level.Debug(logger).Log("msg", "No netlink stats, skipping") logger.Debug("No netlink stats, skipping")
continue continue
} }
@ -141,7 +140,7 @@ func parseNetlinkStats(links []rtnetlink.LinkMessage, filter *deviceFilter, logg
return metrics return metrics
} }
func procNetDevStats(filter *deviceFilter, logger log.Logger) (netDevStats, error) { func procNetDevStats(filter *deviceFilter, logger *slog.Logger) (netDevStats, error) {
metrics := netDevStats{} metrics := netDevStats{}
fs, err := procfs.NewFS(*procPath) fs, err := procfs.NewFS(*procPath)
@ -158,7 +157,7 @@ func procNetDevStats(filter *deviceFilter, logger log.Logger) (netDevStats, erro
name := stats.Name name := stats.Name
if filter.ignored(name) { if filter.ignored(name) {
level.Debug(logger).Log("msg", "Ignoring device", "device", name) logger.Debug("Ignoring device", "device", name)
continue continue
} }

View file

@ -17,10 +17,10 @@
package collector package collector
import ( import (
"io"
"log/slog"
"testing" "testing"
"github.com/go-kit/log"
"github.com/jsimonetti/rtnetlink" "github.com/jsimonetti/rtnetlink"
) )
@ -166,7 +166,7 @@ var links = []rtnetlink.LinkMessage{
func TestNetDevStatsIgnore(t *testing.T) { func TestNetDevStatsIgnore(t *testing.T) {
filter := newDeviceFilter("^veth", "") filter := newDeviceFilter("^veth", "")
netStats := parseNetlinkStats(links, &filter, log.NewNopLogger()) netStats := parseNetlinkStats(links, &filter, slog.New(slog.NewTextHandler(io.Discard, nil)))
if want, got := uint64(10437182923), netStats["wlan0"]["receive_bytes"]; want != got { if want, got := uint64(10437182923), netStats["wlan0"]["receive_bytes"]; want != got {
t.Errorf("want netstat wlan0 bytes %v, got %v", want, got) t.Errorf("want netstat wlan0 bytes %v, got %v", want, got)
@ -199,7 +199,7 @@ func TestNetDevStatsIgnore(t *testing.T) {
func TestNetDevStatsAccept(t *testing.T) { func TestNetDevStatsAccept(t *testing.T) {
filter := newDeviceFilter("", "^💩0$") filter := newDeviceFilter("", "^💩0$")
netStats := parseNetlinkStats(links, &filter, log.NewNopLogger()) netStats := parseNetlinkStats(links, &filter, slog.New(slog.NewTextHandler(io.Discard, nil)))
if want, got := 1, len(netStats); want != got { if want, got := 1, len(netStats); want != got {
t.Errorf("want count of devices to be %d, got %d", want, got) t.Errorf("want count of devices to be %d, got %d", want, got)
@ -230,7 +230,7 @@ func TestNetDevLegacyMetricNames(t *testing.T) {
} }
filter := newDeviceFilter("", "") filter := newDeviceFilter("", "")
netStats := parseNetlinkStats(links, &filter, log.NewNopLogger()) netStats := parseNetlinkStats(links, &filter, slog.New(slog.NewTextHandler(io.Discard, nil)))
for dev, devStats := range netStats { for dev, devStats := range netStats {
legacy(devStats) legacy(devStats)
@ -263,7 +263,7 @@ func TestNetDevLegacyMetricValues(t *testing.T) {
} }
filter := newDeviceFilter("", "^enp0s0f0$") filter := newDeviceFilter("", "^enp0s0f0$")
netStats := parseNetlinkStats(links, &filter, log.NewNopLogger()) netStats := parseNetlinkStats(links, &filter, slog.New(slog.NewTextHandler(io.Discard, nil)))
metrics, ok := netStats["enp0s0f0"] metrics, ok := netStats["enp0s0f0"]
if !ok { if !ok {
t.Error("expected stats for interface enp0s0f0") t.Error("expected stats for interface enp0s0f0")
@ -285,7 +285,7 @@ func TestNetDevLegacyMetricValues(t *testing.T) {
func TestNetDevMetricValues(t *testing.T) { func TestNetDevMetricValues(t *testing.T) {
filter := newDeviceFilter("", "") filter := newDeviceFilter("", "")
netStats := parseNetlinkStats(links, &filter, log.NewNopLogger()) netStats := parseNetlinkStats(links, &filter, slog.New(slog.NewTextHandler(io.Discard, nil)))
for _, msg := range links { for _, msg := range links {
device := msg.Attributes.Name device := msg.Attributes.Name

View file

@ -18,9 +18,7 @@ package collector
import ( import (
"errors" "errors"
"log/slog"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
) )
/* /*
@ -31,7 +29,7 @@ import (
*/ */
import "C" import "C"
func getNetDevStats(filter *deviceFilter, logger log.Logger) (netDevStats, error) { func getNetDevStats(filter *deviceFilter, logger *slog.Logger) (netDevStats, error) {
netDev := netDevStats{} netDev := netDevStats{}
var ifap, ifa *C.struct_ifaddrs var ifap, ifa *C.struct_ifaddrs
@ -47,7 +45,7 @@ func getNetDevStats(filter *deviceFilter, logger log.Logger) (netDevStats, error
dev := C.GoString(ifa.ifa_name) dev := C.GoString(ifa.ifa_name)
if filter.ignored(dev) { if filter.ignored(dev) {
level.Debug(logger).Log("msg", "Ignoring device", "device", dev) logger.Debug("Ignoring device", "device", dev)
continue continue
} }

View file

@ -17,14 +17,13 @@
package collector package collector
import ( import (
"github.com/go-kit/log" "log/slog"
"github.com/go-kit/log/level"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
"unsafe" "unsafe"
) )
func getNetDevStats(filter *deviceFilter, logger log.Logger) (netDevStats, error) { func getNetDevStats(filter *deviceFilter, logger *slog.Logger) (netDevStats, error) {
netDev := netDevStats{} netDev := netDevStats{}
mib := [6]_C_int{unix.CTL_NET, unix.AF_ROUTE, 0, 0, unix.NET_RT_IFLIST, 0} mib := [6]_C_int{unix.CTL_NET, unix.AF_ROUTE, 0, 0, unix.NET_RT_IFLIST, 0}
@ -54,7 +53,7 @@ func getNetDevStats(filter *deviceFilter, logger log.Logger) (netDevStats, error
data := ifm.Data data := ifm.Data
dev := int8ToString(dl.Data[:dl.Nlen]) dev := int8ToString(dl.Data[:dl.Nlen])
if filter.ignored(dev) { if filter.ignored(dev) {
level.Debug(logger).Log("msg", "Ignoring device", "device", dev) logger.Debug("Ignoring device", "device", dev)
continue continue
} }

View file

@ -18,14 +18,14 @@ package collector
import ( import (
"fmt" "fmt"
"log/slog"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
type netisrCollector struct { type netisrCollector struct {
sysctls []bsdSysctl sysctls []bsdSysctl
logger log.Logger logger *slog.Logger
} }
const ( const (
@ -36,7 +36,7 @@ func init() {
registerCollector("netisr", defaultEnabled, NewNetisrCollector) registerCollector("netisr", defaultEnabled, NewNetisrCollector)
} }
func NewNetisrCollector(logger log.Logger) (Collector, error) { func NewNetisrCollector(logger *slog.Logger) (Collector, error) {
return &netisrCollector{ return &netisrCollector{
sysctls: []bsdSysctl{ sysctls: []bsdSysctl{
{ {

View file

@ -21,13 +21,13 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"log/slog"
"os" "os"
"regexp" "regexp"
"strconv" "strconv"
"strings" "strings"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -41,7 +41,7 @@ var (
type netStatCollector struct { type netStatCollector struct {
fieldPattern *regexp.Regexp fieldPattern *regexp.Regexp
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -50,7 +50,7 @@ func init() {
// NewNetStatCollector takes and returns // NewNetStatCollector takes and returns
// a new Collector exposing network stats. // a new Collector exposing network stats.
func NewNetStatCollector(logger log.Logger) (Collector, error) { func NewNetStatCollector(logger *slog.Logger) (Collector, error) {
pattern := regexp.MustCompile(*netStatFields) pattern := regexp.MustCompile(*netStatFields)
return &netStatCollector{ return &netStatCollector{
fieldPattern: pattern, fieldPattern: pattern,

View file

@ -19,10 +19,10 @@ package collector
import ( import (
"fmt" "fmt"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
"log/slog"
"net" "net"
"strconv" "strconv"
"github.com/go-kit/log"
"github.com/jsimonetti/rtnetlink" "github.com/jsimonetti/rtnetlink"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -30,7 +30,7 @@ import (
type networkRouteCollector struct { type networkRouteCollector struct {
routeInfoDesc *prometheus.Desc routeInfoDesc *prometheus.Desc
routesDesc *prometheus.Desc routesDesc *prometheus.Desc
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -38,7 +38,7 @@ func init() {
} }
// NewNetworkRouteCollector returns a new Collector exposing systemd statistics. // NewNetworkRouteCollector returns a new Collector exposing systemd statistics.
func NewNetworkRouteCollector(logger log.Logger) (Collector, error) { func NewNetworkRouteCollector(logger *slog.Logger) (Collector, error) {
const subsystem = "network" const subsystem = "network"
routeInfoDesc := prometheus.NewDesc( routeInfoDesc := prometheus.NewDesc(

View file

@ -19,11 +19,10 @@ package collector
import ( import (
"errors" "errors"
"fmt" "fmt"
"log/slog"
"os" "os"
"reflect" "reflect"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/procfs/nfs" "github.com/prometheus/procfs/nfs"
) )
@ -40,7 +39,7 @@ type nfsCollector struct {
nfsRPCRetransmissionsDesc *prometheus.Desc nfsRPCRetransmissionsDesc *prometheus.Desc
nfsRPCAuthenticationRefreshesDesc *prometheus.Desc nfsRPCAuthenticationRefreshesDesc *prometheus.Desc
nfsProceduresDesc *prometheus.Desc nfsProceduresDesc *prometheus.Desc
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -48,7 +47,7 @@ func init() {
} }
// NewNfsCollector returns a new Collector exposing NFS statistics. // NewNfsCollector returns a new Collector exposing NFS statistics.
func NewNfsCollector(logger log.Logger) (Collector, error) { func NewNfsCollector(logger *slog.Logger) (Collector, error) {
fs, err := nfs.NewFS(*procPath) fs, err := nfs.NewFS(*procPath)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to open procfs: %w", err) return nil, fmt.Errorf("failed to open procfs: %w", err)
@ -100,7 +99,7 @@ func (c *nfsCollector) Update(ch chan<- prometheus.Metric) error {
stats, err := c.fs.ClientRPCStats() stats, err := c.fs.ClientRPCStats()
if err != nil { if err != nil {
if errors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {
level.Debug(c.logger).Log("msg", "Not collecting NFS metrics", "err", err) c.logger.Debug("Not collecting NFS metrics", "err", err)
return ErrNoData return ErrNoData
} }
return fmt.Errorf("failed to retrieve nfs stats: %w", err) return fmt.Errorf("failed to retrieve nfs stats: %w", err)

View file

@ -19,10 +19,9 @@ package collector
import ( import (
"errors" "errors"
"fmt" "fmt"
"log/slog"
"os" "os"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/procfs/nfs" "github.com/prometheus/procfs/nfs"
) )
@ -32,7 +31,7 @@ import (
type nfsdCollector struct { type nfsdCollector struct {
fs nfs.FS fs nfs.FS
requestsDesc *prometheus.Desc requestsDesc *prometheus.Desc
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -44,7 +43,7 @@ const (
) )
// NewNFSdCollector returns a new Collector exposing /proc/net/rpc/nfsd statistics. // NewNFSdCollector returns a new Collector exposing /proc/net/rpc/nfsd statistics.
func NewNFSdCollector(logger log.Logger) (Collector, error) { func NewNFSdCollector(logger *slog.Logger) (Collector, error) {
fs, err := nfs.NewFS(*procPath) fs, err := nfs.NewFS(*procPath)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to open procfs: %w", err) return nil, fmt.Errorf("failed to open procfs: %w", err)
@ -66,7 +65,7 @@ func (c *nfsdCollector) Update(ch chan<- prometheus.Metric) error {
stats, err := c.fs.ServerRPCStats() stats, err := c.fs.ServerRPCStats()
if err != nil { if err != nil {
if errors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {
level.Debug(c.logger).Log("msg", "Not collecting NFSd metrics", "err", err) c.logger.Debug("Not collecting NFSd metrics", "err", err)
return ErrNoData return ErrNoData
} }
return fmt.Errorf("failed to retrieve nfsd stats: %w", err) return fmt.Errorf("failed to retrieve nfsd stats: %w", err)

View file

@ -18,14 +18,13 @@ package collector
import ( import (
"fmt" "fmt"
"log/slog"
"net" "net"
"sync" "sync"
"time" "time"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/beevik/ntp" "github.com/beevik/ntp"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -51,7 +50,7 @@ var (
type ntpCollector struct { type ntpCollector struct {
stratum, leap, rtt, offset, reftime, rootDelay, rootDispersion, sanity typedDesc stratum, leap, rtt, offset, reftime, rootDelay, rootDispersion, sanity typedDesc
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -62,7 +61,7 @@ func init() {
// Default definition of "local" is: // Default definition of "local" is:
// - collector.ntp.server address is a loopback address (or collector.ntp.server-is-mine flag is turned on) // - collector.ntp.server address is a loopback address (or collector.ntp.server-is-mine flag is turned on)
// - the server is reachable with outgoin IP_TTL = 1 // - the server is reachable with outgoin IP_TTL = 1
func NewNtpCollector(logger log.Logger) (Collector, error) { func NewNtpCollector(logger *slog.Logger) (Collector, error) {
ipaddr := net.ParseIP(*ntpServer) ipaddr := net.ParseIP(*ntpServer)
if !*ntpServerIsLocal && (ipaddr == nil || !ipaddr.IsLoopback()) { if !*ntpServerIsLocal && (ipaddr == nil || !ipaddr.IsLoopback()) {
return nil, fmt.Errorf("only IP address of local NTP server is valid for --collector.ntp.server") return nil, fmt.Errorf("only IP address of local NTP server is valid for --collector.ntp.server")
@ -80,7 +79,7 @@ func NewNtpCollector(logger log.Logger) (Collector, error) {
return nil, fmt.Errorf("invalid NTP port number %d; must be between 1 and 65535 inclusive", *ntpServerPort) return nil, fmt.Errorf("invalid NTP port number %d; must be between 1 and 65535 inclusive", *ntpServerPort)
} }
level.Warn(logger).Log("msg", "This collector is deprecated and will be removed in the next major version release.") logger.Warn("This collector is deprecated and will be removed in the next major version release.")
return &ntpCollector{ return &ntpCollector{
stratum: typedDesc{prometheus.NewDesc( stratum: typedDesc{prometheus.NewDesc(
prometheus.BuildFQName(namespace, ntpSubsystem, "stratum"), prometheus.BuildFQName(namespace, ntpSubsystem, "stratum"),

View file

@ -19,17 +19,16 @@ package collector
import ( import (
"errors" "errors"
"fmt" "fmt"
"log/slog"
"os" "os"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/procfs/sysfs" "github.com/prometheus/procfs/sysfs"
) )
type nvmeCollector struct { type nvmeCollector struct {
fs sysfs.FS fs sysfs.FS
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -37,7 +36,7 @@ func init() {
} }
// NewNVMeCollector returns a new Collector exposing NVMe stats. // NewNVMeCollector returns a new Collector exposing NVMe stats.
func NewNVMeCollector(logger log.Logger) (Collector, error) { func NewNVMeCollector(logger *slog.Logger) (Collector, error) {
fs, err := sysfs.NewFS(*sysPath) fs, err := sysfs.NewFS(*sysPath)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to open sysfs: %w", err) return nil, fmt.Errorf("failed to open sysfs: %w", err)
@ -53,7 +52,7 @@ func (c *nvmeCollector) Update(ch chan<- prometheus.Metric) error {
devices, err := c.fs.NVMeClass() devices, err := c.fs.NVMeClass()
if err != nil { if err != nil {
if errors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {
level.Debug(c.logger).Log("msg", "nvme statistics not found, skipping") c.logger.Debug("nvme statistics not found, skipping")
return ErrNoData return ErrNoData
} }
return fmt.Errorf("error obtaining NVMe class info: %w", err) return fmt.Errorf("error obtaining NVMe class info: %w", err)

View file

@ -17,6 +17,7 @@ import (
"encoding/xml" "encoding/xml"
"errors" "errors"
"io" "io"
"log/slog"
"os" "os"
"regexp" "regexp"
"strconv" "strconv"
@ -24,8 +25,6 @@ import (
"sync" "sync"
"time" "time"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
envparse "github.com/hashicorp/go-envparse" envparse "github.com/hashicorp/go-envparse"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -58,7 +57,7 @@ type osRelease struct {
type osReleaseCollector struct { type osReleaseCollector struct {
infoDesc *prometheus.Desc infoDesc *prometheus.Desc
logger log.Logger logger *slog.Logger
os *osRelease os *osRelease
osMutex sync.RWMutex osMutex sync.RWMutex
osReleaseFilenames []string // all os-release file names to check osReleaseFilenames []string // all os-release file names to check
@ -82,7 +81,7 @@ func init() {
} }
// NewOSCollector returns a new Collector exposing os-release information. // NewOSCollector returns a new Collector exposing os-release information.
func NewOSCollector(logger log.Logger) (Collector, error) { func NewOSCollector(logger *slog.Logger) (Collector, error) {
return &osReleaseCollector{ return &osReleaseCollector{
logger: logger, logger: logger,
infoDesc: prometheus.NewDesc( infoDesc: prometheus.NewDesc(
@ -178,7 +177,7 @@ func (c *osReleaseCollector) Update(ch chan<- prometheus.Metric) error {
} }
if errors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {
if i >= (len(c.osReleaseFilenames) - 1) { if i >= (len(c.osReleaseFilenames) - 1) {
level.Debug(c.logger).Log("msg", "no os-release file found", "files", strings.Join(c.osReleaseFilenames, ",")) c.logger.Debug("no os-release file found", "files", strings.Join(c.osReleaseFilenames, ","))
return ErrNoData return ErrNoData
} }
continue continue

View file

@ -14,12 +14,12 @@
package collector package collector
import ( import (
"io"
"log/slog"
"os" "os"
"reflect" "reflect"
"strings" "strings"
"testing" "testing"
"github.com/go-kit/log"
) )
const debianBullseye string = `PRETTY_NAME="Debian GNU/Linux 11 (bullseye)" const debianBullseye string = `PRETTY_NAME="Debian GNU/Linux 11 (bullseye)"
@ -129,7 +129,7 @@ func TestUpdateStruct(t *testing.T) {
} }
wantedVersion := 20.04 wantedVersion := 20.04
collector, err := NewOSCollector(log.NewNopLogger()) collector, err := NewOSCollector(slog.New(slog.NewTextHandler(io.Discard, nil)))
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View file

@ -18,13 +18,12 @@ package collector
import ( import (
"fmt" "fmt"
"log/slog"
"runtime" "runtime"
"strconv" "strconv"
"strings" "strings"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/hodgesds/perf-utils" "github.com/hodgesds/perf-utils"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
@ -189,7 +188,7 @@ type perfCollector struct {
perfSwProfilers map[int]*perf.SoftwareProfiler perfSwProfilers map[int]*perf.SoftwareProfiler
perfCacheProfilers map[int]*perf.CacheProfiler perfCacheProfilers map[int]*perf.CacheProfiler
desc map[string]*prometheus.Desc desc map[string]*prometheus.Desc
logger log.Logger logger *slog.Logger
tracepointCollector *perfTracepointCollector tracepointCollector *perfTracepointCollector
} }
@ -199,7 +198,7 @@ type perfTracepointCollector struct {
// collection order is the sorted configured collection order of the profiler. // collection order is the sorted configured collection order of the profiler.
collectionOrder []string collectionOrder []string
logger log.Logger logger *slog.Logger
profilers map[int]perf.GroupProfiler profilers map[int]perf.GroupProfiler
} }
@ -218,7 +217,7 @@ func (c *perfTracepointCollector) updateCPU(cpu int, ch chan<- prometheus.Metric
profiler := c.profilers[cpu] profiler := c.profilers[cpu]
p := &perf.GroupProfileValue{} p := &perf.GroupProfileValue{}
if err := profiler.Profile(p); err != nil { if err := profiler.Profile(p); err != nil {
level.Error(c.logger).Log("msg", "Failed to collect tracepoint profile", "err", err) c.logger.Error("Failed to collect tracepoint profile", "err", err)
return err return err
} }
@ -240,7 +239,7 @@ func (c *perfTracepointCollector) updateCPU(cpu int, ch chan<- prometheus.Metric
// newPerfTracepointCollector returns a configured perfTracepointCollector. // newPerfTracepointCollector returns a configured perfTracepointCollector.
func newPerfTracepointCollector( func newPerfTracepointCollector(
logger log.Logger, logger *slog.Logger,
tracepointsFlag []string, tracepointsFlag []string,
cpus []int, cpus []int,
) (*perfTracepointCollector, error) { ) (*perfTracepointCollector, error) {
@ -301,7 +300,7 @@ func newPerfTracepointCollector(
// NewPerfCollector returns a new perf based collector, it creates a profiler // NewPerfCollector returns a new perf based collector, it creates a profiler
// per CPU. // per CPU.
func NewPerfCollector(logger log.Logger) (Collector, error) { func NewPerfCollector(logger *slog.Logger) (Collector, error) {
collector := &perfCollector{ collector := &perfCollector{
perfHwProfilers: map[int]*perf.HardwareProfiler{}, perfHwProfilers: map[int]*perf.HardwareProfiler{},
perfSwProfilers: map[int]*perf.SoftwareProfiler{}, perfSwProfilers: map[int]*perf.SoftwareProfiler{},

View file

@ -17,13 +17,14 @@
package collector package collector
import ( import (
"io"
"log/slog"
"os" "os"
"runtime" "runtime"
"strconv" "strconv"
"strings" "strings"
"testing" "testing"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -44,7 +45,7 @@ func canTestPerf(t *testing.T) {
func TestPerfCollector(t *testing.T) { func TestPerfCollector(t *testing.T) {
canTestPerf(t) canTestPerf(t)
collector, err := NewPerfCollector(log.NewNopLogger()) collector, err := NewPerfCollector(slog.New(slog.NewTextHandler(io.Discard, nil)))
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -97,7 +98,7 @@ func TestPerfCollectorStride(t *testing.T) {
} }
} }
perfCPUsFlag = &test.flag perfCPUsFlag = &test.flag
collector, err := NewPerfCollector(log.NewNopLogger()) collector, err := NewPerfCollector(slog.New(slog.NewTextHandler(io.Discard, nil)))
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View file

@ -18,10 +18,10 @@
package collector package collector
import ( import (
"log/slog"
"regexp" "regexp"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -33,14 +33,14 @@ type powerSupplyClassCollector struct {
subsystem string subsystem string
ignoredPattern *regexp.Regexp ignoredPattern *regexp.Regexp
metricDescs map[string]*prometheus.Desc metricDescs map[string]*prometheus.Desc
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
registerCollector("powersupplyclass", defaultEnabled, NewPowerSupplyClassCollector) registerCollector("powersupplyclass", defaultEnabled, NewPowerSupplyClassCollector)
} }
func NewPowerSupplyClassCollector(logger log.Logger) (Collector, error) { func NewPowerSupplyClassCollector(logger *slog.Logger) (Collector, error) {
pattern := regexp.MustCompile(*powerSupplyClassIgnoredPowerSupplies) pattern := regexp.MustCompile(*powerSupplyClassIgnoredPowerSupplies)
return &powerSupplyClassCollector{ return &powerSupplyClassCollector{
subsystem: "power_supply", subsystem: "power_supply",

View file

@ -19,11 +19,10 @@ package collector
import ( import (
"errors" "errors"
"fmt" "fmt"
"log/slog"
"os" "os"
"syscall" "syscall"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/procfs" "github.com/prometheus/procfs"
) )
@ -42,7 +41,7 @@ type pressureStatsCollector struct {
fs procfs.FS fs procfs.FS
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -50,7 +49,7 @@ func init() {
} }
// NewPressureStatsCollector returns a Collector exposing pressure stall information // NewPressureStatsCollector returns a Collector exposing pressure stall information
func NewPressureStatsCollector(logger log.Logger) (Collector, error) { func NewPressureStatsCollector(logger *slog.Logger) (Collector, error) {
fs, err := procfs.NewFS(*procPath) fs, err := procfs.NewFS(*procPath)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to open procfs: %w", err) return nil, fmt.Errorf("failed to open procfs: %w", err)
@ -95,15 +94,15 @@ func NewPressureStatsCollector(logger log.Logger) (Collector, error) {
// Update calls procfs.NewPSIStatsForResource for the different resources and updates the values // Update calls procfs.NewPSIStatsForResource for the different resources and updates the values
func (c *pressureStatsCollector) Update(ch chan<- prometheus.Metric) error { func (c *pressureStatsCollector) Update(ch chan<- prometheus.Metric) error {
for _, res := range psiResources { for _, res := range psiResources {
level.Debug(c.logger).Log("msg", "collecting statistics for resource", "resource", res) c.logger.Debug("collecting statistics for resource", "resource", res)
vals, err := c.fs.PSIStatsForResource(res) vals, err := c.fs.PSIStatsForResource(res)
if err != nil { if err != nil {
if errors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {
level.Debug(c.logger).Log("msg", "pressure information is unavailable, you need a Linux kernel >= 4.20 and/or CONFIG_PSI enabled for your kernel") c.logger.Debug("pressure information is unavailable, you need a Linux kernel >= 4.20 and/or CONFIG_PSI enabled for your kernel")
return ErrNoData return ErrNoData
} }
if errors.Is(err, syscall.ENOTSUP) { if errors.Is(err, syscall.ENOTSUP) {
level.Debug(c.logger).Log("msg", "pressure information is disabled, add psi=1 kernel command line to enable it") c.logger.Debug("pressure information is disabled, add psi=1 kernel command line to enable it")
return ErrNoData return ErrNoData
} }
return fmt.Errorf("failed to retrieve pressure stats: %w", err) return fmt.Errorf("failed to retrieve pressure stats: %w", err)
@ -111,11 +110,11 @@ func (c *pressureStatsCollector) Update(ch chan<- prometheus.Metric) error {
// IRQ pressure does not have 'some' data. // IRQ pressure does not have 'some' data.
// See https://github.com/torvalds/linux/blob/v6.9/include/linux/psi_types.h#L65 // See https://github.com/torvalds/linux/blob/v6.9/include/linux/psi_types.h#L65
if vals.Some == nil && res != "irq" { if vals.Some == nil && res != "irq" {
level.Debug(c.logger).Log("msg", "pressure information returned no 'some' data") c.logger.Debug("pressure information returned no 'some' data")
return ErrNoData return ErrNoData
} }
if vals.Full == nil && res != "cpu" { if vals.Full == nil && res != "cpu" {
level.Debug(c.logger).Log("msg", "pressure information returned no 'full' data") c.logger.Debug("pressure information returned no 'full' data")
return ErrNoData return ErrNoData
} }
switch res { switch res {
@ -130,7 +129,7 @@ func (c *pressureStatsCollector) Update(ch chan<- prometheus.Metric) error {
case "irq": case "irq":
ch <- prometheus.MustNewConstMetric(c.irqFull, prometheus.CounterValue, float64(vals.Full.Total)/1000.0/1000.0) ch <- prometheus.MustNewConstMetric(c.irqFull, prometheus.CounterValue, float64(vals.Full.Total)/1000.0/1000.0)
default: default:
level.Debug(c.logger).Log("msg", "did not account for resource", "resource", res) c.logger.Debug("did not account for resource", "resource", res)
} }
} }

View file

@ -19,14 +19,13 @@ package collector
import ( import (
"errors" "errors"
"fmt" "fmt"
"log/slog"
"os" "os"
"path" "path"
"strconv" "strconv"
"strings" "strings"
"syscall" "syscall"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/procfs" "github.com/prometheus/procfs"
) )
@ -39,7 +38,7 @@ type processCollector struct {
procsState *prometheus.Desc procsState *prometheus.Desc
pidUsed *prometheus.Desc pidUsed *prometheus.Desc
pidMax *prometheus.Desc pidMax *prometheus.Desc
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -47,7 +46,7 @@ func init() {
} }
// NewProcessStatCollector returns a new Collector exposing process data read from the proc filesystem. // NewProcessStatCollector returns a new Collector exposing process data read from the proc filesystem.
func NewProcessStatCollector(logger log.Logger) (Collector, error) { func NewProcessStatCollector(logger *slog.Logger) (Collector, error) {
fs, err := procfs.NewFS(*procPath) fs, err := procfs.NewFS(*procPath)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to open procfs: %w", err) return nil, fmt.Errorf("failed to open procfs: %w", err)
@ -130,10 +129,10 @@ func (c *processCollector) getAllocatedThreads() (int, map[string]int32, int, ma
if err != nil { if err != nil {
// PIDs can vanish between getting the list and getting stats. // PIDs can vanish between getting the list and getting stats.
if c.isIgnoredError(err) { if c.isIgnoredError(err) {
level.Debug(c.logger).Log("msg", "file not found when retrieving stats for pid", "pid", pid.PID, "err", err) c.logger.Debug("file not found when retrieving stats for pid", "pid", pid.PID, "err", err)
continue continue
} }
level.Debug(c.logger).Log("msg", "error reading stat for pid", "pid", pid.PID, "err", err) c.logger.Debug("error reading stat for pid", "pid", pid.PID, "err", err)
return 0, nil, 0, nil, fmt.Errorf("error reading stat for pid %d: %w", pid.PID, err) return 0, nil, 0, nil, fmt.Errorf("error reading stat for pid %d: %w", pid.PID, err)
} }
pids++ pids++
@ -151,17 +150,17 @@ func (c *processCollector) getThreadStates(pid int, pidStat procfs.ProcStat, thr
fs, err := procfs.NewFS(procFilePath(path.Join(strconv.Itoa(pid), "task"))) fs, err := procfs.NewFS(procFilePath(path.Join(strconv.Itoa(pid), "task")))
if err != nil { if err != nil {
if c.isIgnoredError(err) { if c.isIgnoredError(err) {
level.Debug(c.logger).Log("msg", "file not found when retrieving tasks for pid", "pid", pid, "err", err) c.logger.Debug("file not found when retrieving tasks for pid", "pid", pid, "err", err)
return nil return nil
} }
level.Debug(c.logger).Log("msg", "error reading tasks for pid", "pid", pid, "err", err) c.logger.Debug("error reading tasks for pid", "pid", pid, "err", err)
return fmt.Errorf("error reading task for pid %d: %w", pid, err) return fmt.Errorf("error reading task for pid %d: %w", pid, err)
} }
t, err := fs.AllProcs() t, err := fs.AllProcs()
if err != nil { if err != nil {
if c.isIgnoredError(err) { if c.isIgnoredError(err) {
level.Debug(c.logger).Log("msg", "file not found when retrieving tasks for pid", "pid", pid, "err", err) c.logger.Debug("file not found when retrieving tasks for pid", "pid", pid, "err", err)
return nil return nil
} }
return fmt.Errorf("unable to list all threads for pid: %d %w", pid, err) return fmt.Errorf("unable to list all threads for pid: %d %w", pid, err)
@ -175,10 +174,10 @@ func (c *processCollector) getThreadStates(pid int, pidStat procfs.ProcStat, thr
threadStat, err := thread.Stat() threadStat, err := thread.Stat()
if err != nil { if err != nil {
if c.isIgnoredError(err) { if c.isIgnoredError(err) {
level.Debug(c.logger).Log("msg", "file not found when retrieving stats for thread", "pid", pid, "threadId", thread.PID, "err", err) c.logger.Debug("file not found when retrieving stats for thread", "pid", pid, "threadId", thread.PID, "err", err)
continue continue
} }
level.Debug(c.logger).Log("msg", "error reading stat for thread", "pid", pid, "threadId", thread.PID, "err", err) c.logger.Debug("error reading stat for thread", "pid", pid, "threadId", thread.PID, "err", err)
return fmt.Errorf("error reading stat for pid:%d thread:%d err:%w", pid, thread.PID, err) return fmt.Errorf("error reading stat for pid:%d thread:%d err:%w", pid, thread.PID, err)
} }
threadStates[threadStat.State]++ threadStates[threadStat.State]++

View file

@ -17,10 +17,11 @@
package collector package collector
import ( import (
"io"
"log/slog"
"testing" "testing"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
"github.com/prometheus/procfs" "github.com/prometheus/procfs"
) )
@ -33,7 +34,7 @@ func TestReadProcessStatus(t *testing.T) {
if err != nil { if err != nil {
t.Errorf("failed to open procfs: %v", err) t.Errorf("failed to open procfs: %v", err)
} }
c := processCollector{fs: fs, logger: log.NewNopLogger()} c := processCollector{fs: fs, logger: slog.New(slog.NewTextHandler(io.Discard, nil))}
pids, states, threads, _, err := c.getAllocatedThreads() pids, states, threads, _, err := c.getAllocatedThreads()
if err != nil { if err != nil {
t.Fatalf("Cannot retrieve data from procfs getAllocatedThreads function: %v ", err) t.Fatalf("Cannot retrieve data from procfs getAllocatedThreads function: %v ", err)

View file

@ -19,18 +19,17 @@ package collector
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"log/slog"
"os" "os"
"path/filepath" "path/filepath"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/ema/qdisc" "github.com/ema/qdisc"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
type qdiscStatCollector struct { type qdiscStatCollector struct {
logger log.Logger logger *slog.Logger
deviceFilter deviceFilter deviceFilter deviceFilter
bytes typedDesc bytes typedDesc
packets typedDesc packets typedDesc
@ -54,10 +53,10 @@ func init() {
} }
// NewQdiscStatCollector returns a new Collector exposing queuing discipline statistics. // NewQdiscStatCollector returns a new Collector exposing queuing discipline statistics.
func NewQdiscStatCollector(logger log.Logger) (Collector, error) { func NewQdiscStatCollector(logger *slog.Logger) (Collector, error) {
if *oldCollectorQdiskDeviceInclude != "" { if *oldCollectorQdiskDeviceInclude != "" {
if *collectorQdiscDeviceInclude == "" { if *collectorQdiscDeviceInclude == "" {
level.Warn(logger).Log("msg", "--collector.qdisk.device-include is DEPRECATED and will be removed in 2.0.0, use --collector.qdisc.device-include") logger.Warn("--collector.qdisk.device-include is DEPRECATED and will be removed in 2.0.0, use --collector.qdisc.device-include")
*collectorQdiscDeviceInclude = *oldCollectorQdiskDeviceInclude *collectorQdiscDeviceInclude = *oldCollectorQdiskDeviceInclude
} else { } else {
return nil, fmt.Errorf("--collector.qdisk.device-include and --collector.qdisc.device-include are mutually exclusive") return nil, fmt.Errorf("--collector.qdisk.device-include and --collector.qdisc.device-include are mutually exclusive")
@ -66,7 +65,7 @@ func NewQdiscStatCollector(logger log.Logger) (Collector, error) {
if *oldCollectorQdiskDeviceExclude != "" { if *oldCollectorQdiskDeviceExclude != "" {
if *collectorQdiscDeviceExclude == "" { if *collectorQdiscDeviceExclude == "" {
level.Warn(logger).Log("msg", "--collector.qdisk.device-exclude is DEPRECATED and will be removed in 2.0.0, use --collector.qdisc.device-exclude") logger.Warn("--collector.qdisk.device-exclude is DEPRECATED and will be removed in 2.0.0, use --collector.qdisc.device-exclude")
*collectorQdiscDeviceExclude = *oldCollectorQdiskDeviceExclude *collectorQdiscDeviceExclude = *oldCollectorQdiskDeviceExclude
} else { } else {
return nil, fmt.Errorf("--collector.qdisk.device-exclude and --collector.qdisc.device-exclude are mutually exclusive") return nil, fmt.Errorf("--collector.qdisk.device-exclude and --collector.qdisc.device-exclude are mutually exclusive")

View file

@ -19,12 +19,11 @@ package collector
import ( import (
"errors" "errors"
"fmt" "fmt"
"log/slog"
"os" "os"
"strconv" "strconv"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/procfs/sysfs" "github.com/prometheus/procfs/sysfs"
) )
@ -33,7 +32,7 @@ const raplCollectorSubsystem = "rapl"
type raplCollector struct { type raplCollector struct {
fs sysfs.FS fs sysfs.FS
logger log.Logger logger *slog.Logger
joulesMetricDesc *prometheus.Desc joulesMetricDesc *prometheus.Desc
} }
@ -47,7 +46,7 @@ var (
) )
// NewRaplCollector returns a new Collector exposing RAPL metrics. // NewRaplCollector returns a new Collector exposing RAPL metrics.
func NewRaplCollector(logger log.Logger) (Collector, error) { func NewRaplCollector(logger *slog.Logger) (Collector, error) {
fs, err := sysfs.NewFS(*sysPath) fs, err := sysfs.NewFS(*sysPath)
if err != nil { if err != nil {
@ -74,11 +73,11 @@ func (c *raplCollector) Update(ch chan<- prometheus.Metric) error {
zones, err := sysfs.GetRaplZones(c.fs) zones, err := sysfs.GetRaplZones(c.fs)
if err != nil { if err != nil {
if errors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {
level.Debug(c.logger).Log("msg", "Platform doesn't have powercap files present", "err", err) c.logger.Debug("Platform doesn't have powercap files present", "err", err)
return ErrNoData return ErrNoData
} }
if errors.Is(err, os.ErrPermission) { if errors.Is(err, os.ErrPermission) {
level.Debug(c.logger).Log("msg", "Can't access powercap files", "err", err) c.logger.Debug("Can't access powercap files", "err", err)
return ErrNoData return ErrNoData
} }
return fmt.Errorf("failed to retrieve rapl stats: %w", err) return fmt.Errorf("failed to retrieve rapl stats: %w", err)
@ -88,7 +87,7 @@ func (c *raplCollector) Update(ch chan<- prometheus.Metric) error {
microJoules, err := rz.GetEnergyMicrojoules() microJoules, err := rz.GetEnergyMicrojoules()
if err != nil { if err != nil {
if errors.Is(err, os.ErrPermission) { if errors.Is(err, os.ErrPermission) {
level.Debug(c.logger).Log("msg", "Can't access energy_uj file", "zone", rz, "err", err) c.logger.Debug("Can't access energy_uj file", "zone", rz, "err", err)
return ErrNoData return ErrNoData
} }
return err return err

View file

@ -18,10 +18,9 @@ package collector
import ( import (
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus-community/go-runit/runit" "github.com/prometheus-community/go-runit/runit"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"log/slog"
) )
var runitServiceDir = kingpin.Flag("collector.runit.servicedir", "Path to runit service directory.").Default("/etc/service").String() var runitServiceDir = kingpin.Flag("collector.runit.servicedir", "Path to runit service directory.").Default("/etc/service").String()
@ -31,7 +30,7 @@ type runitCollector struct {
stateDesired typedDesc stateDesired typedDesc
stateNormal typedDesc stateNormal typedDesc
stateTimestamp typedDesc stateTimestamp typedDesc
logger log.Logger logger *slog.Logger
} }
func init() { func init() {
@ -39,14 +38,14 @@ func init() {
} }
// NewRunitCollector returns a new Collector exposing runit statistics. // NewRunitCollector returns a new Collector exposing runit statistics.
func NewRunitCollector(logger log.Logger) (Collector, error) { func NewRunitCollector(logger *slog.Logger) (Collector, error) {
var ( var (
subsystem = "service" subsystem = "service"
constLabels = prometheus.Labels{"supervisor": "runit"} constLabels = prometheus.Labels{"supervisor": "runit"}
labelNames = []string{"service"} labelNames = []string{"service"}
) )
level.Warn(logger).Log("msg", "This collector is deprecated and will be removed in the next major version release.") logger.Warn("This collector is deprecated and will be removed in the next major version release.")
return &runitCollector{ return &runitCollector{
state: typedDesc{prometheus.NewDesc( state: typedDesc{prometheus.NewDesc(
@ -82,11 +81,11 @@ func (c *runitCollector) Update(ch chan<- prometheus.Metric) error {
for _, service := range services { for _, service := range services {
status, err := service.Status() status, err := service.Status()
if err != nil { if err != nil {
level.Debug(c.logger).Log("msg", "Couldn't get status", "service", service.Name, "err", err) c.logger.Debug("Couldn't get status", "service", service.Name, "err", err)
continue continue
} }
level.Debug(c.logger).Log("msg", "duration", "service", service.Name, "status", status.State, "pid", status.Pid, "duration_seconds", status.Duration) c.logger.Debug("duration", "service", service.Name, "status", status.State, "pid", status.Pid, "duration_seconds", status.Duration)
ch <- c.state.mustNewConstMetric(float64(status.State), service.Name) ch <- c.state.mustNewConstMetric(float64(status.State), service.Name)
ch <- c.stateDesired.mustNewConstMetric(float64(status.Want), service.Name) ch <- c.stateDesired.mustNewConstMetric(float64(status.Want), service.Name)
ch <- c.stateTimestamp.mustNewConstMetric(float64(status.Timestamp.Unix()), service.Name) ch <- c.stateTimestamp.mustNewConstMetric(float64(status.Timestamp.Unix()), service.Name)

Some files were not shown because too many files have changed in this diff Show more