From 89c832feb0d830031cb43db11684034c02e497f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan-Otto=20Kr=C3=B6pke?= Date: Sat, 24 Aug 2024 19:14:38 +0200 Subject: [PATCH] chore: pass context aware logger to collectors (#1582) --- exporter.go | 10 +- go.mod | 5 +- go.sum | 2 + pkg/collector/ad/ad.go | 24 ++-- pkg/collector/adcs/adcs.go | 24 ++-- pkg/collector/adfs/adfs.go | 18 +-- pkg/collector/cache/cache.go | 25 ++-- pkg/collector/collector.go | 132 ++++++++---------- pkg/collector/container/container.go | 42 +++--- pkg/collector/cpu/cpu.go | 30 ++-- pkg/collector/cpu_info/cpu_info.go | 18 +-- pkg/collector/cs/cs.go | 18 +-- pkg/collector/dfsr/dfsr.go | 39 +++--- pkg/collector/dhcp/dhcp.go | 18 +-- pkg/collector/diskdrive/diskdrive.go | 18 +-- pkg/collector/dns/dns.go | 24 ++-- pkg/collector/exchange/exchange.go | 72 +++++----- pkg/collector/fsrmquota/fsrmquota.go | 24 ++-- pkg/collector/handler.go | 14 +- pkg/collector/hyperv/hyperv.go | 120 ++++++++-------- pkg/collector/iis/iis.go | 58 ++++---- pkg/collector/license/license.go | 18 +-- pkg/collector/logical_disk/logical_disk.go | 29 ++-- pkg/collector/logon/logon.go | 24 ++-- pkg/collector/memory/memory.go | 25 ++-- .../mscluster_cluster/mscluster_cluster.go | 18 +-- .../mscluster_network/mscluster_network.go | 18 +-- .../mscluster_node/mscluster_node.go | 18 +-- .../mscluster_resource/mscluster_resource.go | 18 +-- .../mscluster_resourcegroup.go | 18 +-- pkg/collector/msmq/msmq.go | 28 ++-- pkg/collector/mssql/mssql.go | 102 +++++++------- pkg/collector/net/net.go | 25 ++-- .../netframework_clrexceptions.go | 24 ++-- .../netframework_clrinterop.go | 24 ++-- .../netframework_clrjit.go | 24 ++-- .../netframework_clrloading.go | 24 ++-- .../netframework_clrlocksandthreads.go | 24 ++-- .../netframework_clrmemory.go | 24 ++-- .../netframework_clrremoting.go | 24 ++-- .../netframework_clrsecurity.go | 24 ++-- pkg/collector/nps/nps.go | 32 ++--- pkg/collector/os/os.go | 29 ++-- pkg/collector/physical_disk/physical_disk.go | 25 ++-- pkg/collector/printer/printer.go | 32 ++--- pkg/collector/process/process.go | 26 ++-- pkg/collector/prometheus.go | 6 +- pkg/collector/remote_fx/remote_fx.go | 34 ++--- .../scheduled_task/scheduled_task.go | 18 +-- pkg/collector/service/service.go | 60 ++++---- pkg/collector/smb/smb.go | 25 ++-- pkg/collector/smbclient/smbclient.go | 25 ++-- pkg/collector/smtp/smtp.go | 29 ++-- pkg/collector/system/system.go | 25 ++-- pkg/collector/tcp/tcp.go | 27 ++-- .../teradici_pcoip/teradici_pcoip.go | 59 ++++---- .../terminal_services/terminal_services.go | 46 +++--- pkg/collector/textfile/textfile.go | 44 +++--- pkg/collector/textfile/textfile_test_test.go | 14 +- pkg/collector/thermalzone/thermalzone.go | 24 ++-- pkg/collector/time/time.go | 25 ++-- pkg/collector/types.go | 13 +- pkg/collector/vmware/vmware.go | 32 ++--- pkg/collector/vmware_blast/vmware_blast.go | 115 ++++++++------- pkg/testutils/testutils.go | 7 +- 65 files changed, 876 insertions(+), 1164 deletions(-) diff --git a/exporter.go b/exporter.go index e4ffc2476..45e52a7af 100644 --- a/exporter.go +++ b/exporter.go @@ -12,6 +12,7 @@ import ( "context" "encoding/json" + "errors" "fmt" "net/http" "net/http/pprof" @@ -202,15 +203,14 @@ func main() { enabledCollectorList := utils.ExpandEnabledCollectors(*enabledCollectors) collectors.Enable(enabledCollectorList) - collectors.SetLogger(logger) // Initialize collectors before loading - err = collectors.Build() + err = collectors.Build(logger) if err != nil { _ = level.Error(logger).Log("msg", "Couldn't load collectors", "err", err) os.Exit(1) } - err = collectors.SetPerfCounterQuery() + err = collectors.SetPerfCounterQuery(logger) if err != nil { _ = level.Error(logger).Log("msg", "Couldn't set performance counter query", "err", err) os.Exit(1) @@ -229,7 +229,7 @@ func main() { _ = level.Info(logger).Log("msg", fmt.Sprintf("Enabled collectors: %v", strings.Join(enabledCollectorList, ", "))) mux := http.NewServeMux() - mux.HandleFunc(*metricsPath, withConcurrencyLimit(*maxRequests, collectors.BuildServeHTTP(*disableExporterMetrics, *timeoutMargin))) + mux.HandleFunc(*metricsPath, withConcurrencyLimit(*maxRequests, collectors.BuildServeHTTP(logger, *disableExporterMetrics, *timeoutMargin))) mux.HandleFunc("/health", func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "application/json") _, err := fmt.Fprintln(w, `{"status":"ok"}`) @@ -274,7 +274,7 @@ func main() { } go func() { - if err := web.ListenAndServe(server, webConfig, logger); err != nil { + if err := web.ListenAndServe(server, webConfig, logger); err != nil && !errors.Is(err, http.ErrServerClosed) { _ = level.Error(logger).Log("msg", "cannot start windows_exporter", "err", err) os.Exit(1) } diff --git a/go.mod b/go.mod index 4cc7cff21..705bee4d2 100644 --- a/go.mod +++ b/go.mod @@ -21,7 +21,10 @@ require ( gopkg.in/yaml.v3 v3.0.1 ) -require github.com/pkg/errors v0.9.1 +require ( + github.com/google/uuid v1.6.0 + github.com/pkg/errors v0.9.1 +) require ( github.com/Microsoft/go-winio v0.6.2 // indirect diff --git a/go.sum b/go.sum index 91e89f5da..d7f216066 100644 --- a/go.sum +++ b/go.sum @@ -63,6 +63,8 @@ github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/jpillora/backoff v1.0.0 h1:uvFg412JmmHBHw7iwprIxkPMI+sGQ4kzOWsMeHnm2EA= github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA= diff --git a/pkg/collector/ad/ad.go b/pkg/collector/ad/ad.go index 3e0de9f13..6c02a57fe 100644 --- a/pkg/collector/ad/ad.go +++ b/pkg/collector/ad/ad.go @@ -22,7 +22,6 @@ var ConfigDefaults = Config{} // A Collector is a Prometheus Collector for WMI Win32_PerfRawData_DirectoryServices_DirectoryServices metrics. type Collector struct { config Config - logger log.Logger addressBookClientSessions *prometheus.Desc addressBookOperationsTotal *prometheus.Desc @@ -88,7 +87,7 @@ type Collector struct { tombstonesObjectsVisitedTotal *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -97,8 +96,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -110,11 +107,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{}, nil } @@ -122,7 +115,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.addressBookOperationsTotal = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "address_book_operations_total"), "", @@ -502,9 +495,10 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collect(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting ad metrics", "err", err) +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collect(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting ad metrics", "err", err) return err } return nil @@ -662,9 +656,9 @@ type Win32_PerfRawData_DirectoryServices_DirectoryServices struct { TransitivesuboperationsPersec uint32 } -func (c *Collector) collect(ch chan<- prometheus.Metric) error { +func (c *Collector) collect(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []Win32_PerfRawData_DirectoryServices_DirectoryServices - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } diff --git a/pkg/collector/adcs/adcs.go b/pkg/collector/adcs/adcs.go index f91f86fc8..d0a35e336 100644 --- a/pkg/collector/adcs/adcs.go +++ b/pkg/collector/adcs/adcs.go @@ -23,7 +23,6 @@ var ConfigDefaults = Config{} type Collector struct { config Config - logger log.Logger challengeResponseProcessingTime *prometheus.Desc challengeResponsesPerSecond *prometheus.Desc @@ -40,7 +39,7 @@ type Collector struct { signedCertificateTimestampListsPerSecond *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -49,8 +48,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -62,11 +59,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{"Certification Authority"}, nil } @@ -74,7 +67,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.requestsPerSecond = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "requests_total"), "Total certificate requests processed", @@ -157,9 +150,10 @@ func (c *Collector) Build() error { return nil } -func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collectADCSCounters(ctx, ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting ADCS metrics", "err", err) +func (c *Collector) Collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collectADCSCounters(ctx, logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting ADCS metrics", "err", err) return err } return nil @@ -182,12 +176,12 @@ type perflibADCS struct { SignedCertificateTimestampListProcessingTime float64 `perflib:"Signed Certificate Timestamp List processing time (ms)"` } -func (c *Collector) collectADCSCounters(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collectADCSCounters(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { dst := make([]perflibADCS, 0) if _, ok := ctx.PerfObjects["Certification Authority"]; !ok { return errors.New("perflib did not contain an entry for Certification Authority") } - err := perflib.UnmarshalObject(ctx.PerfObjects["Certification Authority"], &dst, c.logger) + err := perflib.UnmarshalObject(ctx.PerfObjects["Certification Authority"], &dst, logger) if err != nil { return err } diff --git a/pkg/collector/adfs/adfs.go b/pkg/collector/adfs/adfs.go index e50fbef72..71db7c23b 100644 --- a/pkg/collector/adfs/adfs.go +++ b/pkg/collector/adfs/adfs.go @@ -20,7 +20,6 @@ var ConfigDefaults = Config{} type Collector struct { config Config - logger log.Logger adLoginConnectionFailures *prometheus.Desc artifactDBFailures *prometheus.Desc @@ -67,7 +66,7 @@ type Collector struct { wstrustTokenRequests *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -76,8 +75,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -89,11 +86,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{"AD FS"}, nil } @@ -101,7 +94,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.adLoginConnectionFailures = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "ad_login_connection_failures_total"), "Total number of connection failures to an Active Directory domain controller", @@ -410,9 +403,10 @@ type perflibADFS struct { FederationMetadataRequests float64 `perflib:"Federation Metadata Requests"` } -func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) Collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var adfsData []perflibADFS - err := perflib.UnmarshalObject(ctx.PerfObjects["AD FS"], &adfsData, c.logger) + err := perflib.UnmarshalObject(ctx.PerfObjects["AD FS"], &adfsData, logger) if err != nil { return err } diff --git a/pkg/collector/cache/cache.go b/pkg/collector/cache/cache.go index 5c1b9d25f..8c52f4297 100644 --- a/pkg/collector/cache/cache.go +++ b/pkg/collector/cache/cache.go @@ -21,7 +21,6 @@ var ConfigDefaults = Config{} // A Collector is a Prometheus Collector for Perflib Cache metrics. type Collector struct { config Config - logger log.Logger asyncCopyReadsTotal *prometheus.Desc asyncDataMapsTotal *prometheus.Desc @@ -54,7 +53,7 @@ type Collector struct { syncPinReadsTotal *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -63,8 +62,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -76,11 +73,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{"Cache"}, nil } @@ -88,7 +81,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.asyncCopyReadsTotal = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "async_copy_reads_total"), "(AsyncCopyReadsTotal)", @@ -267,9 +260,10 @@ func (c *Collector) Build() error { } // Collect implements the Collector interface. -func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collect(ctx, ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting cache metrics", "err", err) +func (c *Collector) Collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collect(ctx, logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting cache metrics", "err", err) return err } @@ -311,9 +305,10 @@ type perflibCache struct { DataMapHitsPercent float64 `perflib:"Data Map Hits %"` } -func (c *Collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var dst []perflibCache // Single-instance class, array is required but will have single entry. - if err := perflib.UnmarshalObject(ctx.PerfObjects["Cache"], &dst, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["Cache"], &dst, logger); err != nil { return err } diff --git a/pkg/collector/collector.go b/pkg/collector/collector.go index 2ea6a347e..e2972b004 100644 --- a/pkg/collector/collector.go +++ b/pkg/collector/collector.go @@ -89,64 +89,64 @@ func NewBuilderWithFlags[C Collector](fn BuilderWithFlags[C]) BuilderWithFlags[C // NewWithConfig To be called by the external libraries for collector initialization without running kingpin.Parse // //goland:noinspection GoUnusedExportedFunction -func NewWithConfig(logger log.Logger, config Config) Collectors { +func NewWithConfig(config Config) Collectors { collectors := map[string]Collector{} - collectors[ad.Name] = ad.New(logger, &config.AD) - collectors[adcs.Name] = adcs.New(logger, &config.ADCS) - collectors[adfs.Name] = adfs.New(logger, &config.ADFS) - collectors[cache.Name] = cache.New(logger, &config.Cache) - collectors[container.Name] = container.New(logger, &config.Container) - collectors[cpu.Name] = cpu.New(logger, &config.CPU) - collectors[cpu_info.Name] = cpu_info.New(logger, &config.CPUInfo) - collectors[cs.Name] = cs.New(logger, &config.Cs) - collectors[dfsr.Name] = dfsr.New(logger, &config.DFSR) - collectors[dhcp.Name] = dhcp.New(logger, &config.Dhcp) - collectors[diskdrive.Name] = diskdrive.New(logger, &config.DiskDrive) - collectors[dns.Name] = dns.New(logger, &config.DNS) - collectors[exchange.Name] = exchange.New(logger, &config.Exchange) - collectors[fsrmquota.Name] = fsrmquota.New(logger, &config.Fsrmquota) - collectors[hyperv.Name] = hyperv.New(logger, &config.Hyperv) - collectors[iis.Name] = iis.New(logger, &config.IIS) - collectors[license.Name] = license.New(logger, &config.License) - collectors[logical_disk.Name] = logical_disk.New(logger, &config.LogicalDisk) - collectors[logon.Name] = logon.New(logger, &config.Logon) - collectors[memory.Name] = memory.New(logger, &config.Memory) - collectors[mscluster_cluster.Name] = mscluster_cluster.New(logger, &config.MsclusterCluster) - collectors[mscluster_network.Name] = mscluster_network.New(logger, &config.MsclusterNetwork) - collectors[mscluster_node.Name] = mscluster_node.New(logger, &config.MsclusterNode) - collectors[mscluster_resource.Name] = mscluster_resource.New(logger, &config.MsclusterResource) - collectors[mscluster_resourcegroup.Name] = mscluster_resourcegroup.New(logger, &config.MsclusterResourceGroup) - collectors[msmq.Name] = msmq.New(logger, &config.Msmq) - collectors[mssql.Name] = mssql.New(logger, &config.Mssql) - collectors[net.Name] = net.New(logger, &config.Net) - collectors[netframework_clrexceptions.Name] = netframework_clrexceptions.New(logger, &config.NetframeworkClrexceptions) - collectors[netframework_clrinterop.Name] = netframework_clrinterop.New(logger, &config.NetframeworkClrinterop) - collectors[netframework_clrjit.Name] = netframework_clrjit.New(logger, &config.NetframeworkClrjit) - collectors[netframework_clrloading.Name] = netframework_clrloading.New(logger, &config.NetframeworkClrloading) - collectors[netframework_clrlocksandthreads.Name] = netframework_clrlocksandthreads.New(logger, &config.NetframeworkClrlocksandthreads) - collectors[netframework_clrmemory.Name] = netframework_clrmemory.New(logger, &config.NetframeworkClrmemory) - collectors[netframework_clrremoting.Name] = netframework_clrremoting.New(logger, &config.NetframeworkClrremoting) - collectors[netframework_clrsecurity.Name] = netframework_clrsecurity.New(logger, &config.NetframeworkClrsecurity) - collectors[nps.Name] = nps.New(logger, &config.Nps) - collectors[os.Name] = os.New(logger, &config.Os) - collectors[physical_disk.Name] = physical_disk.New(logger, &config.PhysicalDisk) - collectors[printer.Name] = printer.New(logger, &config.Printer) - collectors[process.Name] = process.New(logger, &config.Process) - collectors[remote_fx.Name] = remote_fx.New(logger, &config.RemoteFx) - collectors[scheduled_task.Name] = scheduled_task.New(logger, &config.ScheduledTask) - collectors[service.Name] = service.New(logger, &config.Service) - collectors[smb.Name] = smb.New(logger, &config.SMB) - collectors[smbclient.Name] = smbclient.New(logger, &config.SMBClient) - collectors[smtp.Name] = smtp.New(logger, &config.SMTP) - collectors[system.Name] = system.New(logger, &config.System) - collectors[teradici_pcoip.Name] = teradici_pcoip.New(logger, &config.TeradiciPcoip) - collectors[tcp.Name] = tcp.New(logger, &config.TCP) - collectors[terminal_services.Name] = terminal_services.New(logger, &config.TerminalServices) - collectors[textfile.Name] = textfile.New(logger, &config.Textfile) - collectors[thermalzone.Name] = thermalzone.New(logger, &config.Thermalzone) - collectors[time.Name] = time.New(logger, &config.Time) - collectors[vmware.Name] = vmware.New(logger, &config.Vmware) - collectors[vmware_blast.Name] = vmware_blast.New(logger, &config.VmwareBlast) + collectors[ad.Name] = ad.New(&config.AD) + collectors[adcs.Name] = adcs.New(&config.ADCS) + collectors[adfs.Name] = adfs.New(&config.ADFS) + collectors[cache.Name] = cache.New(&config.Cache) + collectors[container.Name] = container.New(&config.Container) + collectors[cpu.Name] = cpu.New(&config.CPU) + collectors[cpu_info.Name] = cpu_info.New(&config.CPUInfo) + collectors[cs.Name] = cs.New(&config.Cs) + collectors[dfsr.Name] = dfsr.New(&config.DFSR) + collectors[dhcp.Name] = dhcp.New(&config.Dhcp) + collectors[diskdrive.Name] = diskdrive.New(&config.DiskDrive) + collectors[dns.Name] = dns.New(&config.DNS) + collectors[exchange.Name] = exchange.New(&config.Exchange) + collectors[fsrmquota.Name] = fsrmquota.New(&config.Fsrmquota) + collectors[hyperv.Name] = hyperv.New(&config.Hyperv) + collectors[iis.Name] = iis.New(&config.IIS) + collectors[license.Name] = license.New(&config.License) + collectors[logical_disk.Name] = logical_disk.New(&config.LogicalDisk) + collectors[logon.Name] = logon.New(&config.Logon) + collectors[memory.Name] = memory.New(&config.Memory) + collectors[mscluster_cluster.Name] = mscluster_cluster.New(&config.MsclusterCluster) + collectors[mscluster_network.Name] = mscluster_network.New(&config.MsclusterNetwork) + collectors[mscluster_node.Name] = mscluster_node.New(&config.MsclusterNode) + collectors[mscluster_resource.Name] = mscluster_resource.New(&config.MsclusterResource) + collectors[mscluster_resourcegroup.Name] = mscluster_resourcegroup.New(&config.MsclusterResourceGroup) + collectors[msmq.Name] = msmq.New(&config.Msmq) + collectors[mssql.Name] = mssql.New(&config.Mssql) + collectors[net.Name] = net.New(&config.Net) + collectors[netframework_clrexceptions.Name] = netframework_clrexceptions.New(&config.NetframeworkClrexceptions) + collectors[netframework_clrinterop.Name] = netframework_clrinterop.New(&config.NetframeworkClrinterop) + collectors[netframework_clrjit.Name] = netframework_clrjit.New(&config.NetframeworkClrjit) + collectors[netframework_clrloading.Name] = netframework_clrloading.New(&config.NetframeworkClrloading) + collectors[netframework_clrlocksandthreads.Name] = netframework_clrlocksandthreads.New(&config.NetframeworkClrlocksandthreads) + collectors[netframework_clrmemory.Name] = netframework_clrmemory.New(&config.NetframeworkClrmemory) + collectors[netframework_clrremoting.Name] = netframework_clrremoting.New(&config.NetframeworkClrremoting) + collectors[netframework_clrsecurity.Name] = netframework_clrsecurity.New(&config.NetframeworkClrsecurity) + collectors[nps.Name] = nps.New(&config.Nps) + collectors[os.Name] = os.New(&config.Os) + collectors[physical_disk.Name] = physical_disk.New(&config.PhysicalDisk) + collectors[printer.Name] = printer.New(&config.Printer) + collectors[process.Name] = process.New(&config.Process) + collectors[remote_fx.Name] = remote_fx.New(&config.RemoteFx) + collectors[scheduled_task.Name] = scheduled_task.New(&config.ScheduledTask) + collectors[service.Name] = service.New(&config.Service) + collectors[smb.Name] = smb.New(&config.SMB) + collectors[smbclient.Name] = smbclient.New(&config.SMBClient) + collectors[smtp.Name] = smtp.New(&config.SMTP) + collectors[system.Name] = system.New(&config.System) + collectors[teradici_pcoip.Name] = teradici_pcoip.New(&config.TeradiciPcoip) + collectors[tcp.Name] = tcp.New(&config.TCP) + collectors[terminal_services.Name] = terminal_services.New(&config.TerminalServices) + collectors[textfile.Name] = textfile.New(&config.Textfile) + collectors[thermalzone.Name] = thermalzone.New(&config.Thermalzone) + collectors[time.Name] = time.New(&config.Time) + collectors[vmware.Name] = vmware.New(&config.Vmware) + collectors[vmware_blast.Name] = vmware_blast.New(&config.VmwareBlast) return New(collectors) } @@ -158,15 +158,7 @@ func New(collectors Map) Collectors { } } -func (c *Collectors) SetLogger(logger log.Logger) { - c.logger = logger - - for _, collector := range c.collectors { - collector.SetLogger(logger) - } -} - -func (c *Collectors) SetPerfCounterQuery() error { +func (c *Collectors) SetPerfCounterQuery(logger log.Logger) error { var ( err error @@ -177,7 +169,7 @@ func (c *Collectors) SetPerfCounterQuery() error { perfCounterDependencies := make([]string, 0, len(c.collectors)) for _, collector := range c.collectors { - perfCounterNames, err = collector.GetPerfCounter() + perfCounterNames, err = collector.GetPerfCounter(logger) if err != nil { return err } @@ -205,11 +197,11 @@ func (c *Collectors) Enable(enabledCollectors []string) { } // Build To be called by the exporter for collector initialization. -func (c *Collectors) Build() error { +func (c *Collectors) Build(logger log.Logger) error { var err error for _, collector := range c.collectors { - if err = collector.Build(); err != nil { + if err = collector.Build(logger); err != nil { return err } } @@ -232,7 +224,7 @@ func (c *Collectors) Close() error { errs := make([]error, 0, len(c.collectors)) for _, collector := range c.collectors { - if err := collector.Build(); err != nil { + if err := collector.Close(); err != nil { errs = append(errs, err) } } diff --git a/pkg/collector/container/container.go b/pkg/collector/container/container.go index 27f1c1c82..d5cf8ee71 100644 --- a/pkg/collector/container/container.go +++ b/pkg/collector/container/container.go @@ -23,7 +23,6 @@ var ConfigDefaults = Config{} // A Collector is a Prometheus Collector for containers metrics. type Collector struct { config Config - logger log.Logger // Presence containerAvailable *prometheus.Desc @@ -57,7 +56,7 @@ type Collector struct { } // New constructs a new Collector. -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -66,8 +65,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -79,11 +76,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{}, nil } @@ -91,7 +84,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.containerAvailable = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "available"), "Available", @@ -205,27 +198,28 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collect(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting collector metrics", "err", err) +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collect(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting collector metrics", "err", err) return err } return nil } // containerClose closes the container resource. -func (c *Collector) containerClose(container hcsshim.Container) { +func (c *Collector) containerClose(logger log.Logger, container hcsshim.Container) { err := container.Close() if err != nil { - _ = level.Error(c.logger).Log("err", err) + _ = level.Error(logger).Log("err", err) } } -func (c *Collector) collect(ch chan<- prometheus.Metric) error { +func (c *Collector) collect(logger log.Logger, ch chan<- prometheus.Metric) error { // Types Container is passed to get the containers compute systems only containers, err := hcsshim.GetContainers(hcsshim.ComputeSystemQuery{Types: []string{"Container"}}) if err != nil { - _ = level.Error(c.logger).Log("msg", "Err in Getting containers", "err", err) + _ = level.Error(logger).Log("msg", "Err in Getting containers", "err", err) return err } @@ -247,16 +241,16 @@ func (c *Collector) collect(ch chan<- prometheus.Metric) error { func() { container, err := hcsshim.OpenContainer(containerDetails.ID) if container != nil { - defer c.containerClose(container) + defer c.containerClose(logger, container) } if err != nil { - _ = level.Error(c.logger).Log("msg", "err in opening container", "containerId", containerDetails.ID, "err", err) + _ = level.Error(logger).Log("msg", "err in opening container", "containerId", containerDetails.ID, "err", err) return } cstats, err := container.Statistics() if err != nil { - _ = level.Error(c.logger).Log("msg", "err in fetching container Statistics", "containerId", containerDetails.ID, "err", err) + _ = level.Error(logger).Log("msg", "err in fetching container Statistics", "containerId", containerDetails.ID, "err", err) return } @@ -334,19 +328,19 @@ func (c *Collector) collect(ch chan<- prometheus.Metric) error { hnsEndpoints, err := hcsshim.HNSListEndpointRequest() if err != nil { - _ = level.Warn(c.logger).Log("msg", "Failed to collect network stats for containers") + _ = level.Warn(logger).Log("msg", "Failed to collect network stats for containers") return err } if len(hnsEndpoints) == 0 { - _ = level.Info(c.logger).Log("msg", "No network stats for containers to collect") + _ = level.Info(logger).Log("msg", "No network stats for containers to collect") return nil } for _, endpoint := range hnsEndpoints { endpointStats, err := hcsshim.GetHNSEndpointStats(endpoint.Id) if err != nil { - _ = level.Warn(c.logger).Log("msg", "Failed to collect network stats for interface "+endpoint.Id, "err", err) + _ = level.Warn(logger).Log("msg", "Failed to collect network stats for interface "+endpoint.Id, "err", err) continue } @@ -355,7 +349,7 @@ func (c *Collector) collect(ch chan<- prometheus.Metric) error { endpointId := strings.ToUpper(endpoint.Id) if !ok { - _ = level.Warn(c.logger).Log("msg", "Failed to collect network stats for container "+containerId) + _ = level.Warn(logger).Log("msg", "Failed to collect network stats for container "+containerId) continue } diff --git a/pkg/collector/cpu/cpu.go b/pkg/collector/cpu/cpu.go index fa50d5c45..0fb586a53 100644 --- a/pkg/collector/cpu/cpu.go +++ b/pkg/collector/cpu/cpu.go @@ -21,7 +21,6 @@ var ConfigDefaults = Config{} type Collector struct { config Config - logger log.Logger cStateSecondsTotal *prometheus.Desc timeTotal *prometheus.Desc @@ -38,7 +37,7 @@ type Collector struct { processorPrivilegedUtility *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -47,8 +46,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -60,11 +57,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { if winversion.WindowsVersionFloat > 6.05 { return []string{"Processor Information"}, nil } @@ -75,7 +68,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.cStateSecondsTotal = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "cstate_seconds_total"), "Time spent in low-power idle state", @@ -193,12 +186,13 @@ func (c *Collector) Build() error { return nil } -func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) Collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) if winversion.WindowsVersionFloat > 6.05 { - return c.CollectFull(ctx, ch) + return c.CollectFull(ctx, logger, ch) } - return c.CollectBasic(ctx, ch) + return c.CollectBasic(ctx, logger, ch) } type perflibProcessor struct { @@ -220,9 +214,10 @@ type perflibProcessor struct { PercentUserTime float64 `perflib:"% User Time"` } -func (c *Collector) CollectBasic(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) CollectBasic(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) data := make([]perflibProcessor, 0) - err := perflib.UnmarshalObject(ctx.PerfObjects["Processor"], &data, c.logger) + err := perflib.UnmarshalObject(ctx.PerfObjects["Processor"], &data, logger) if err != nil { return err } @@ -329,9 +324,10 @@ type perflibProcessorInformation struct { UserTimeSeconds float64 `perflib:"% User Time"` } -func (c *Collector) CollectFull(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) CollectFull(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) data := make([]perflibProcessorInformation, 0) - err := perflib.UnmarshalObject(ctx.PerfObjects["Processor Information"], &data, c.logger) + err := perflib.UnmarshalObject(ctx.PerfObjects["Processor Information"], &data, logger) if err != nil { return err } diff --git a/pkg/collector/cpu_info/cpu_info.go b/pkg/collector/cpu_info/cpu_info.go index 815f0e78c..9aafd8ba5 100644 --- a/pkg/collector/cpu_info/cpu_info.go +++ b/pkg/collector/cpu_info/cpu_info.go @@ -28,12 +28,11 @@ var ConfigDefaults = Config{} // A Collector is a Prometheus Collector for a few WMI metrics in Win32_Processor. type Collector struct { config Config - logger log.Logger cpuInfo *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -42,8 +41,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -55,11 +52,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{}, nil } @@ -67,7 +60,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.cpuInfo = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, "", Name), "Labelled CPU information as provided by Win32_Processor", @@ -98,9 +91,10 @@ type win32_Processor struct { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) if err := c.collect(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting cpu_info metrics", "err", err) + _ = level.Error(logger).Log("msg", "failed collecting cpu_info metrics", "err", err) return err } return nil diff --git a/pkg/collector/cs/cs.go b/pkg/collector/cs/cs.go index fba90765f..4068fbd1e 100644 --- a/pkg/collector/cs/cs.go +++ b/pkg/collector/cs/cs.go @@ -20,14 +20,13 @@ var ConfigDefaults = Config{} // A Collector is a Prometheus Collector for WMI metrics. type Collector struct { config Config - logger log.Logger physicalMemoryBytes *prometheus.Desc logicalProcessors *prometheus.Desc hostname *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -36,8 +35,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -49,11 +46,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{}, nil } @@ -61,7 +54,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.logicalProcessors = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "logical_processors"), "ComputerSystem.NumberOfLogicalProcessors", @@ -89,9 +82,10 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) if err := c.collect(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting cs metrics", "err", err) + _ = level.Error(logger).Log("msg", "failed collecting cs metrics", "err", err) return err } return nil diff --git a/pkg/collector/dfsr/dfsr.go b/pkg/collector/dfsr/dfsr.go index a65c93778..621e63928 100644 --- a/pkg/collector/dfsr/dfsr.go +++ b/pkg/collector/dfsr/dfsr.go @@ -27,7 +27,6 @@ var ConfigDefaults = Config{ // Collector contains the metric and state data of the DFSR collectors. type Collector struct { config Config - logger log.Logger // connection source connectionBandwidthSavingsUsingDFSReplicationTotal *prometheus.Desc @@ -80,7 +79,7 @@ type Collector struct { dfsrChildCollectors []dfsrCollectorFunc } -type dfsrCollectorFunc func(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error +type dfsrCollectorFunc func(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error // Map Perflib sources to DFSR Collector names // e.g, volume -> DFS Replication Service Volumes. @@ -98,7 +97,7 @@ func dfsrGetPerfObjectName(collector string) string { return prefix + suffix } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -111,8 +110,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -139,11 +136,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { // Perflib sources are dynamic, depending on the enabled child collectors expandedChildCollectors := slices.Compact(c.config.CollectorsEnabled) perflibDependencies := make([]string, 0, len(expandedChildCollectors)) @@ -159,8 +152,10 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { - _ = level.Info(c.logger).Log("msg", "dfsr collector is in an experimental state! Metrics for this collector have not been tested.") +func (c *Collector) Build(logger log.Logger) error { + logger = log.With(logger, "collector", Name) + + _ = level.Info(logger).Log("msg", "dfsr collector is in an experimental state! Metrics for this collector have not been tested.") // connection c.connectionBandwidthSavingsUsingDFSReplicationTotal = prometheus.NewDesc( @@ -479,9 +474,10 @@ func (c *Collector) getDFSRChildCollectors(enabledCollectors []string) []dfsrCol // Collect implements the Collector interface. // Sends metric values for each metric to the provided prometheus Metric channel. -func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) Collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) for _, fn := range c.dfsrChildCollectors { - err := fn(ctx, ch) + err := fn(ctx, logger, ch) if err != nil { return err } @@ -504,9 +500,10 @@ type PerflibDFSRConnection struct { SizeOfFilesReceivedTotal float64 `perflib:"Size of Files Received"` } -func (c *Collector) collectConnection(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collectConnection(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var dst []PerflibDFSRConnection - if err := perflib.UnmarshalObject(ctx.PerfObjects["DFS Replication Connections"], &dst, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["DFS Replication Connections"], &dst, logger); err != nil { return err } @@ -610,9 +607,10 @@ type perflibDFSRFolder struct { UpdatesDroppedTotal float64 `perflib:"Updates Dropped"` } -func (c *Collector) collectFolder(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collectFolder(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var dst []perflibDFSRFolder - if err := perflib.UnmarshalObject(ctx.PerfObjects["DFS Replicated Folders"], &dst, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["DFS Replicated Folders"], &dst, logger); err != nil { return err } @@ -820,9 +818,10 @@ type perflibDFSRVolume struct { USNJournalUnreadPercentage float64 `perflib:"USN Journal Records Unread Percentage"` } -func (c *Collector) collectVolume(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collectVolume(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var dst []perflibDFSRVolume - if err := perflib.UnmarshalObject(ctx.PerfObjects["DFS Replication Service volumes"], &dst, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["DFS Replication Service volumes"], &dst, logger); err != nil { return err } diff --git a/pkg/collector/dhcp/dhcp.go b/pkg/collector/dhcp/dhcp.go index d181ccb01..42b2c080c 100644 --- a/pkg/collector/dhcp/dhcp.go +++ b/pkg/collector/dhcp/dhcp.go @@ -19,7 +19,6 @@ var ConfigDefaults = Config{} // A Collector is a Prometheus Collector perflib DHCP metrics. type Collector struct { config Config - logger log.Logger acksTotal *prometheus.Desc activeQueueLength *prometheus.Desc @@ -48,7 +47,7 @@ type Collector struct { requestsTotal *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -57,8 +56,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -70,11 +67,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{"DHCP Server"}, nil } @@ -82,7 +75,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.packetsReceivedTotal = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "packets_received_total"), "Total number of packets received by the DHCP server (PacketsReceivedTotal)", @@ -267,9 +260,10 @@ type dhcpPerf struct { FailoverBndupdDropped float64 `perflib:"Failover: BndUpd Dropped."` } -func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) Collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var dhcpPerfs []dhcpPerf - if err := perflib.UnmarshalObject(ctx.PerfObjects["DHCP Server"], &dhcpPerfs, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["DHCP Server"], &dhcpPerfs, logger); err != nil { return err } diff --git a/pkg/collector/diskdrive/diskdrive.go b/pkg/collector/diskdrive/diskdrive.go index bfc89b2a8..d39508303 100644 --- a/pkg/collector/diskdrive/diskdrive.go +++ b/pkg/collector/diskdrive/diskdrive.go @@ -26,7 +26,6 @@ var ConfigDefaults = Config{} // A Collector is a Prometheus Collector for a few WMI metrics in Win32_DiskDrive. type Collector struct { config Config - logger log.Logger availability *prometheus.Desc diskInfo *prometheus.Desc @@ -35,7 +34,7 @@ type Collector struct { status *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -44,8 +43,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -57,11 +54,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{}, nil } @@ -69,7 +62,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.diskInfo = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "info"), "General drive information", @@ -162,9 +155,10 @@ var ( ) // Collect sends the metric values for each metric to the provided prometheus Metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) if err := c.collect(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting disk_drive_info metrics", "err", err) + _ = level.Error(logger).Log("msg", "failed collecting disk_drive_info metrics", "err", err) return err } return nil diff --git a/pkg/collector/dns/dns.go b/pkg/collector/dns/dns.go index acd72a8c9..ea7744cfe 100644 --- a/pkg/collector/dns/dns.go +++ b/pkg/collector/dns/dns.go @@ -22,7 +22,6 @@ var ConfigDefaults = Config{} // A Collector is a Prometheus Collector for WMI Win32_PerfRawData_DNS_DNS metrics. type Collector struct { config Config - logger log.Logger dynamicUpdatesFailures *prometheus.Desc dynamicUpdatesQueued *prometheus.Desc @@ -48,7 +47,7 @@ type Collector struct { zoneTransferSuccessSent *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -57,8 +56,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -70,11 +67,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{}, nil } @@ -82,7 +75,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.zoneTransferRequestsReceived = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "zone_transfer_requests_received_total"), "Number of zone transfer requests (AXFR/IXFR) received by the master DNS server", @@ -220,9 +213,10 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collect(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting dns metrics", "err", err) +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collect(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting dns metrics", "err", err) return err } return nil @@ -274,9 +268,9 @@ type Win32_PerfRawData_DNS_DNS struct { ZoneTransferSOARequestSent uint32 } -func (c *Collector) collect(ch chan<- prometheus.Metric) error { +func (c *Collector) collect(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []Win32_PerfRawData_DNS_DNS - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } diff --git a/pkg/collector/exchange/exchange.go b/pkg/collector/exchange/exchange.go index fd6b3a56b..d89d9e140 100644 --- a/pkg/collector/exchange/exchange.go +++ b/pkg/collector/exchange/exchange.go @@ -39,7 +39,6 @@ var ConfigDefaults = Config{ type Collector struct { config Config - logger log.Logger activeMailboxDeliveryQueueLength *prometheus.Desc activeSyncRequestsPerSec *prometheus.Desc @@ -83,7 +82,7 @@ type Collector struct { enabledCollectors []string } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -96,8 +95,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -163,11 +160,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{ "MSExchange ADAccess Processes", "MSExchangeTransport Queues", @@ -186,7 +179,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { // desc creates a new prometheus description desc := func(metricName string, description string, labels ...string) *prometheus.Desc { return prometheus.NewDesc( @@ -252,8 +245,9 @@ func (c *Collector) Build() error { } // Collect collects exchange metrics and sends them to prometheus. -func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { - collectorFuncs := map[string]func(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error{ +func (c *Collector) Collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + collectorFuncs := map[string]func(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error{ "ADAccessProcesses": c.collectADAccessProcesses, "TransportQueues": c.collectTransportQueues, "HttpProxy": c.collectHTTPProxy, @@ -267,8 +261,8 @@ func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metri } for _, collectorName := range c.enabledCollectors { - if err := collectorFuncs[collectorName](ctx, ch); err != nil { - _ = level.Error(c.logger).Log("msg", "Error in "+collectorName, "err", err) + if err := collectorFuncs[collectorName](ctx, logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "Error in "+collectorName, "err", err) return err } } @@ -286,9 +280,10 @@ type perflibADAccessProcesses struct { LongRunningLDAPOperationsPerMin float64 `perflib:"Long Running LDAP Operations/min"` } -func (c *Collector) collectADAccessProcesses(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collectADAccessProcesses(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var data []perflibADAccessProcesses - if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange ADAccess Processes"], &data, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange ADAccess Processes"], &data, logger); err != nil { return err } @@ -344,9 +339,10 @@ type perflibAvailabilityService struct { RequestsSec float64 `perflib:"Availability Requests (sec)"` } -func (c *Collector) collectAvailabilityService(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collectAvailabilityService(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var data []perflibAvailabilityService - if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange Availability Service"], &data, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange Availability Service"], &data, logger); err != nil { return err } @@ -372,9 +368,10 @@ type perflibHTTPProxy struct { ProxyRequestsPerSec float64 `perflib:"Proxy Requests/Sec"` } -func (c *Collector) collectHTTPProxy(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collectHTTPProxy(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var data []perflibHTTPProxy - if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange HttpProxy"], &data, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange HttpProxy"], &data, logger); err != nil { return err } @@ -426,9 +423,10 @@ type perflibOWA struct { RequestsPerSec float64 `perflib:"Requests/sec"` } -func (c *Collector) collectOWA(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collectOWA(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var data []perflibOWA - if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange OWA"], &data, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange OWA"], &data, logger); err != nil { return err } @@ -454,9 +452,10 @@ type perflibActiveSync struct { SyncCommandsPerSec float64 `perflib:"Sync Commands/sec"` } -func (c *Collector) collectActiveSync(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collectActiveSync(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var data []perflibActiveSync - if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange ActiveSync"], &data, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange ActiveSync"], &data, logger); err != nil { return err } @@ -490,9 +489,10 @@ type perflibRPCClientAccess struct { UserCount float64 `perflib:"User Count"` } -func (c *Collector) collectRPC(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collectRPC(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var data []perflibRPCClientAccess - if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange RpcClientAccess"], &data, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange RpcClientAccess"], &data, logger); err != nil { return err } @@ -546,9 +546,10 @@ type perflibTransportQueues struct { PoisonQueueLength float64 `perflib:"Poison Queue Length"` } -func (c *Collector) collectTransportQueues(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collectTransportQueues(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var data []perflibTransportQueues - if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchangeTransport Queues"], &data, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchangeTransport Queues"], &data, logger); err != nil { return err } @@ -620,9 +621,10 @@ type perflibWorkloadManagementWorkloads struct { IsActive float64 `perflib:"Active"` } -func (c *Collector) collectWorkloadManagementWorkloads(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collectWorkloadManagementWorkloads(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var data []perflibWorkloadManagementWorkloads - if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange WorkloadManagement Workloads"], &data, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange WorkloadManagement Workloads"], &data, logger); err != nil { return err } @@ -671,9 +673,10 @@ type perflibAutodiscover struct { RequestsPerSec float64 `perflib:"Requests/sec"` } -func (c *Collector) collectAutoDiscover(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collectAutoDiscover(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var data []perflibAutodiscover - if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchangeAutodiscover"], &data, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchangeAutodiscover"], &data, logger); err != nil { return err } for _, autodisc := range data { @@ -691,9 +694,10 @@ type perflibMapiHttpEmsmdb struct { ActiveUserCount float64 `perflib:"Active User Count"` } -func (c *Collector) collectMapiHttpEmsmdb(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collectMapiHttpEmsmdb(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var data []perflibMapiHttpEmsmdb - if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange MapiHttp Emsmdb"], &data, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange MapiHttp Emsmdb"], &data, logger); err != nil { return err } diff --git a/pkg/collector/fsrmquota/fsrmquota.go b/pkg/collector/fsrmquota/fsrmquota.go index a8204c39a..8c5c8d3ba 100644 --- a/pkg/collector/fsrmquota/fsrmquota.go +++ b/pkg/collector/fsrmquota/fsrmquota.go @@ -20,7 +20,6 @@ var ConfigDefaults = Config{} type Collector struct { config Config - logger log.Logger quotasCount *prometheus.Desc peakUsage *prometheus.Desc @@ -34,7 +33,7 @@ type Collector struct { template *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -43,8 +42,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -56,11 +53,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{}, nil } @@ -68,7 +61,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.quotasCount = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "count"), "Number of Quotas", @@ -128,9 +121,10 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collect(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting fsrmquota metrics", "err", err) +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collect(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting fsrmquota metrics", "err", err) return err } return nil @@ -153,9 +147,9 @@ type MSFT_FSRMQuota struct { SoftLimit bool } -func (c *Collector) collect(ch chan<- prometheus.Metric) error { +func (c *Collector) collect(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []MSFT_FSRMQuota - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) var count int diff --git a/pkg/collector/handler.go b/pkg/collector/handler.go index 334458f50..8e0858361 100644 --- a/pkg/collector/handler.go +++ b/pkg/collector/handler.go @@ -11,13 +11,14 @@ import ( "github.com/go-kit/log" "github.com/go-kit/log/level" + "github.com/google/uuid" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/collectors" "github.com/prometheus/client_golang/prometheus/collectors/version" "github.com/prometheus/client_golang/prometheus/promhttp" ) -func (c *Collectors) BuildServeHTTP(disableExporterMetrics bool, timeoutMargin float64) http.HandlerFunc { +func (c *Collectors) BuildServeHTTP(logger log.Logger, disableExporterMetrics bool, timeoutMargin float64) http.HandlerFunc { collectorFactory := func(timeout time.Duration, requestedCollectors []string) (error, *Prometheus) { filteredCollectors := make(map[string]Collector) // scrape all enabled collectors if no collector is requested @@ -33,15 +34,16 @@ func (c *Collectors) BuildServeHTTP(disableExporterMetrics bool, timeoutMargin f } filtered := Collectors{ - logger: c.logger, collectors: filteredCollectors, perfCounterQuery: c.perfCounterQuery, } - return nil, NewPrometheus(timeout, &filtered, c.logger) + return nil, NewPrometheus(timeout, &filtered, logger) } return func(w http.ResponseWriter, r *http.Request) { + logger := log.With(logger, "remote", r.RemoteAddr, "correlation_id", uuid.New().String()) + const defaultTimeout = 10.0 var timeoutSeconds float64 @@ -49,7 +51,7 @@ func (c *Collectors) BuildServeHTTP(disableExporterMetrics bool, timeoutMargin f var err error timeoutSeconds, err = strconv.ParseFloat(v, 64) if err != nil { - _ = level.Warn(c.logger).Log("msg", fmt.Sprintf("Couldn't parse X-Prometheus-Scrape-Timeout-Seconds: %q. Defaulting timeout to %f", v, defaultTimeout)) + _ = level.Warn(logger).Log("msg", fmt.Sprintf("Couldn't parse X-Prometheus-Scrape-Timeout-Seconds: %q. Defaulting timeout to %f", v, defaultTimeout)) } } if timeoutSeconds == 0 { @@ -60,7 +62,7 @@ func (c *Collectors) BuildServeHTTP(disableExporterMetrics bool, timeoutMargin f reg := prometheus.NewRegistry() err, wc := collectorFactory(time.Duration(timeoutSeconds*float64(time.Second)), r.URL.Query()["collect[]"]) if err != nil { - _ = level.Warn(c.logger).Log("msg", "Couldn't create filtered metrics handler", "err", err) + _ = level.Warn(logger).Log("msg", "Couldn't create filtered metrics handler", "err", err) w.WriteHeader(http.StatusBadRequest) w.Write([]byte(fmt.Sprintf("Couldn't create filtered metrics handler: %s", err))) //nolint:errcheck return @@ -76,7 +78,7 @@ func (c *Collectors) BuildServeHTTP(disableExporterMetrics bool, timeoutMargin f } h := promhttp.HandlerFor(reg, promhttp.HandlerOpts{ - ErrorLog: stdlog.New(log.NewStdlibAdapter(level.Error(c.logger)), "", stdlog.Lshortfile), + ErrorLog: stdlog.New(log.NewStdlibAdapter(level.Error(logger)), "", stdlog.Lshortfile), }) h.ServeHTTP(w, r) } diff --git a/pkg/collector/hyperv/hyperv.go b/pkg/collector/hyperv/hyperv.go index 9e6aba98e..56beba58b 100644 --- a/pkg/collector/hyperv/hyperv.go +++ b/pkg/collector/hyperv/hyperv.go @@ -23,7 +23,6 @@ var ConfigDefaults = Config{} // Collector is a Prometheus Collector for hyper-v. type Collector struct { config Config - logger log.Logger // Win32_PerfRawData_VmmsVirtualMachineStats_HyperVVirtualMachineHealthSummary healthCritical *prometheus.Desc @@ -140,7 +139,7 @@ type Collector struct { vmMemoryRemovedMemory *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -149,8 +148,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -162,11 +159,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{}, nil } @@ -174,7 +167,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { buildSubsystemName := func(component string) string { return "hyperv_" + component } c.healthCritical = prometheus.NewDesc( @@ -754,64 +747,65 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collectVmHealth(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting hyperV health status metrics", "err", err) +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collectVmHealth(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting hyperV health status metrics", "err", err) return err } - if err := c.collectVmVid(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting hyperV pages metrics", "err", err) + if err := c.collectVmVid(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting hyperV pages metrics", "err", err) return err } - if err := c.collectVmHv(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting hyperV hv status metrics", "err", err) + if err := c.collectVmHv(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting hyperV hv status metrics", "err", err) return err } - if err := c.collectVmProcessor(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting hyperV processor metrics", "err", err) + if err := c.collectVmProcessor(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting hyperV processor metrics", "err", err) return err } - if err := c.collectHostLPUsage(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting hyperV host logical processors metrics", "err", err) + if err := c.collectHostLPUsage(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting hyperV host logical processors metrics", "err", err) return err } - if err := c.collectHostCpuUsage(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting hyperV host CPU metrics", "err", err) + if err := c.collectHostCpuUsage(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting hyperV host CPU metrics", "err", err) return err } - if err := c.collectVmCpuUsage(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting hyperV VM CPU metrics", "err", err) + if err := c.collectVmCpuUsage(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting hyperV VM CPU metrics", "err", err) return err } - if err := c.collectVmSwitch(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting hyperV switch metrics", "err", err) + if err := c.collectVmSwitch(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting hyperV switch metrics", "err", err) return err } - if err := c.collectVmEthernet(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting hyperV ethernet metrics", "err", err) + if err := c.collectVmEthernet(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting hyperV ethernet metrics", "err", err) return err } - if err := c.collectVmStorage(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting hyperV virtual storage metrics", "err", err) + if err := c.collectVmStorage(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting hyperV virtual storage metrics", "err", err) return err } - if err := c.collectVmNetwork(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting hyperV virtual network metrics", "err", err) + if err := c.collectVmNetwork(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting hyperV virtual network metrics", "err", err) return err } - if err := c.collectVmMemory(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting hyperV virtual memory metrics", "err", err) + if err := c.collectVmMemory(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting hyperV virtual memory metrics", "err", err) return err } @@ -824,9 +818,9 @@ type Win32_PerfRawData_VmmsVirtualMachineStats_HyperVVirtualMachineHealthSummary HealthOk uint32 } -func (c *Collector) collectVmHealth(ch chan<- prometheus.Metric) error { +func (c *Collector) collectVmHealth(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []Win32_PerfRawData_VmmsVirtualMachineStats_HyperVVirtualMachineHealthSummary - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } @@ -856,9 +850,9 @@ type Win32_PerfRawData_VidPerfProvider_HyperVVMVidPartition struct { RemotePhysicalPages uint64 } -func (c *Collector) collectVmVid(ch chan<- prometheus.Metric) error { +func (c *Collector) collectVmVid(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []Win32_PerfRawData_VidPerfProvider_HyperVVMVidPartition - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } @@ -919,9 +913,9 @@ type Win32_PerfRawData_HvStats_HyperVHypervisorRootPartition struct { VirtualTLBPages uint64 } -func (c *Collector) collectVmHv(ch chan<- prometheus.Metric) error { +func (c *Collector) collectVmHv(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []Win32_PerfRawData_HvStats_HyperVHypervisorRootPartition - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } @@ -1056,9 +1050,9 @@ type Win32_PerfRawData_HvStats_HyperVHypervisor struct { VirtualProcessors uint64 } -func (c *Collector) collectVmProcessor(ch chan<- prometheus.Metric) error { +func (c *Collector) collectVmProcessor(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []Win32_PerfRawData_HvStats_HyperVHypervisor - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } @@ -1088,9 +1082,9 @@ type Win32_PerfRawData_HvStats_HyperVHypervisorLogicalProcessor struct { PercentTotalRunTime uint } -func (c *Collector) collectHostLPUsage(ch chan<- prometheus.Metric) error { +func (c *Collector) collectHostLPUsage(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []Win32_PerfRawData_HvStats_HyperVHypervisorLogicalProcessor - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } @@ -1102,7 +1096,7 @@ func (c *Collector) collectHostLPUsage(ch chan<- prometheus.Metric) error { // The name format is Hv LP parts := strings.Split(obj.Name, " ") if len(parts) != 3 { - _ = level.Warn(c.logger).Log("msg", fmt.Sprintf("Unexpected format of Name in collectHostLPUsage: %q", obj.Name)) + _ = level.Warn(logger).Log("msg", fmt.Sprintf("Unexpected format of Name in collectHostLPUsage: %q", obj.Name)) continue } coreId := parts[2] @@ -1142,9 +1136,9 @@ type Win32_PerfRawData_HvStats_HyperVHypervisorRootVirtualProcessor struct { CPUWaitTimePerDispatch uint64 } -func (c *Collector) collectHostCpuUsage(ch chan<- prometheus.Metric) error { +func (c *Collector) collectHostCpuUsage(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []Win32_PerfRawData_HvStats_HyperVHypervisorRootVirtualProcessor - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } @@ -1156,7 +1150,7 @@ func (c *Collector) collectHostCpuUsage(ch chan<- prometheus.Metric) error { // The name format is Root VP parts := strings.Split(obj.Name, " ") if len(parts) != 3 { - _ = level.Warn(c.logger).Log("msg", "Unexpected format of Name in collectHostCpuUsage: "+obj.Name) + _ = level.Warn(logger).Log("msg", "Unexpected format of Name in collectHostCpuUsage: "+obj.Name) continue } coreId := parts[2] @@ -1210,9 +1204,9 @@ type Win32_PerfRawData_HvStats_HyperVHypervisorVirtualProcessor struct { CPUWaitTimePerDispatch uint64 } -func (c *Collector) collectVmCpuUsage(ch chan<- prometheus.Metric) error { +func (c *Collector) collectVmCpuUsage(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []Win32_PerfRawData_HvStats_HyperVHypervisorVirtualProcessor - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } @@ -1224,12 +1218,12 @@ func (c *Collector) collectVmCpuUsage(ch chan<- prometheus.Metric) error { // The name format is :Hv VP parts := strings.Split(obj.Name, ":") if len(parts) != 2 { - _ = level.Warn(c.logger).Log("msg", fmt.Sprintf("Unexpected format of Name in collectVmCpuUsage: %q, expected %q. Skipping.", obj.Name, ":Hv VP ")) + _ = level.Warn(logger).Log("msg", fmt.Sprintf("Unexpected format of Name in collectVmCpuUsage: %q, expected %q. Skipping.", obj.Name, ":Hv VP ")) continue } coreParts := strings.Split(parts[1], " ") if len(coreParts) != 3 { - _ = level.Warn(c.logger).Log("msg", fmt.Sprintf("Unexpected format of core identifier in collectVmCpuUsage: %q, expected %q. Skipping.", parts[1], "Hv VP ")) + _ = level.Warn(logger).Log("msg", fmt.Sprintf("Unexpected format of core identifier in collectVmCpuUsage: %q, expected %q. Skipping.", parts[1], "Hv VP ")) continue } vmName := parts[0] @@ -1303,9 +1297,9 @@ type Win32_PerfRawData_NvspSwitchStats_HyperVVirtualSwitch struct { PurgedMacAddressesPersec uint64 } -func (c *Collector) collectVmSwitch(ch chan<- prometheus.Metric) error { +func (c *Collector) collectVmSwitch(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []Win32_PerfRawData_NvspSwitchStats_HyperVVirtualSwitch - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } @@ -1468,9 +1462,9 @@ type Win32_PerfRawData_EthernetPerfProvider_HyperVLegacyNetworkAdapter struct { FramesSentPersec uint64 } -func (c *Collector) collectVmEthernet(ch chan<- prometheus.Metric) error { +func (c *Collector) collectVmEthernet(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []Win32_PerfRawData_EthernetPerfProvider_HyperVLegacyNetworkAdapter - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } @@ -1537,9 +1531,9 @@ type Win32_PerfRawData_Counters_HyperVVirtualStorageDevice struct { WriteOperationsPerSec uint64 } -func (c *Collector) collectVmStorage(ch chan<- prometheus.Metric) error { +func (c *Collector) collectVmStorage(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []Win32_PerfRawData_Counters_HyperVVirtualStorageDevice - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } @@ -1606,9 +1600,9 @@ type Win32_PerfRawData_NvspNicStats_HyperVVirtualNetworkAdapter struct { PacketsSentPersec uint64 } -func (c *Collector) collectVmNetwork(ch chan<- prometheus.Metric) error { +func (c *Collector) collectVmNetwork(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []Win32_PerfRawData_NvspNicStats_HyperVVirtualNetworkAdapter - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } @@ -1679,9 +1673,9 @@ type Win32_PerfRawData_BalancerStats_HyperVDynamicMemoryVM struct { RemovedMemory uint64 } -func (c *Collector) collectVmMemory(ch chan<- prometheus.Metric) error { +func (c *Collector) collectVmMemory(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []Win32_PerfRawData_BalancerStats_HyperVDynamicMemoryVM - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } diff --git a/pkg/collector/iis/iis.go b/pkg/collector/iis/iis.go index bf0bc234b..db40ccc4c 100644 --- a/pkg/collector/iis/iis.go +++ b/pkg/collector/iis/iis.go @@ -35,7 +35,6 @@ var ConfigDefaults = Config{ type Collector struct { config Config - logger log.Logger info *prometheus.Desc @@ -162,7 +161,7 @@ type Collector struct { iisVersion simpleVersion } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -187,8 +186,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -252,11 +249,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{ "Web Service", "APP_POOL_WAS", @@ -269,8 +262,10 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { - c.iisVersion = getIISVersion(c.logger) +func (c *Collector) Build(logger log.Logger) error { + logger = log.With(logger, "collector", Name) + + c.iisVersion = getIISVersion(logger) c.info = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "info"), @@ -932,24 +927,25 @@ func getIISVersion(logger log.Logger) simpleVersion { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collectWebService(ctx, ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting iis metrics", "err", err) +func (c *Collector) Collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collectWebService(ctx, logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting iis metrics", "err", err) return err } - if err := c.collectAPP_POOL_WAS(ctx, ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting iis metrics", "err", err) + if err := c.collectAPP_POOL_WAS(ctx, logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting iis metrics", "err", err) return err } - if err := c.collectW3SVC_W3WP(ctx, ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting iis metrics", "err", err) + if err := c.collectW3SVC_W3WP(ctx, logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting iis metrics", "err", err) return err } - if err := c.collectWebServiceCache(ctx, ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting iis metrics", "err", err) + if err := c.collectWebServiceCache(ctx, logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting iis metrics", "err", err) return err } @@ -1046,9 +1042,10 @@ func dedupIISNames[V hasGetIISName](services []V) map[string]V { return webServiceDeDuplicated } -func (c *Collector) collectWebService(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collectWebService(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var webService []perflibWebService - if err := perflib.UnmarshalObject(ctx.PerfObjects["Web Service"], &webService, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["Web Service"], &webService, logger); err != nil { return err } @@ -1338,9 +1335,10 @@ var applicationStates = map[uint32]string{ 7: "Delete Pending", } -func (c *Collector) collectAPP_POOL_WAS(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collectAPP_POOL_WAS(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var APP_POOL_WAS []perflibAPP_POOL_WAS - if err := perflib.UnmarshalObject(ctx.PerfObjects["APP_POOL_WAS"], &APP_POOL_WAS, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["APP_POOL_WAS"], &APP_POOL_WAS, logger); err != nil { return err } @@ -1515,9 +1513,10 @@ type perflibW3SVC_W3WP_IIS8 struct { WebSocketConnectionsRejected float64 `perflib:"WebSocket Connections Rejected / Sec"` } -func (c *Collector) collectW3SVC_W3WP(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collectW3SVC_W3WP(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var W3SVC_W3WP []perflibW3SVC_W3WP - if err := perflib.UnmarshalObject(ctx.PerfObjects["W3SVC_W3WP"], &W3SVC_W3WP, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["W3SVC_W3WP"], &W3SVC_W3WP, logger); err != nil { return err } @@ -1775,7 +1774,7 @@ func (c *Collector) collectW3SVC_W3WP(ctx *types.ScrapeContext, ch chan<- promet if c.iisVersion.major >= 8 { var W3SVC_W3WP_IIS8 []perflibW3SVC_W3WP_IIS8 - if err := perflib.UnmarshalObject(ctx.PerfObjects["W3SVC_W3WP"], &W3SVC_W3WP_IIS8, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["W3SVC_W3WP"], &W3SVC_W3WP_IIS8, logger); err != nil { return err } @@ -1912,9 +1911,10 @@ type perflibWebServiceCache struct { ServiceCache_OutputCacheQueriesTotal float64 } -func (c *Collector) collectWebServiceCache(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collectWebServiceCache(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var WebServiceCache []perflibWebServiceCache - if err := perflib.UnmarshalObject(ctx.PerfObjects["Web Service Cache"], &WebServiceCache, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["Web Service Cache"], &WebServiceCache, logger); err != nil { return err } diff --git a/pkg/collector/license/license.go b/pkg/collector/license/license.go index eeff70534..692d70480 100644 --- a/pkg/collector/license/license.go +++ b/pkg/collector/license/license.go @@ -28,12 +28,11 @@ var ConfigDefaults = Config{} // A Collector is a Prometheus Collector for WMI Win32_PerfRawData_DNS_DNS metrics. type Collector struct { config Config - logger log.Logger licenseStatus *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -42,8 +41,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -55,11 +52,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{}, nil } @@ -67,7 +60,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.licenseStatus = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "status"), "Status of windows license", @@ -80,9 +73,10 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) if err := c.collect(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting license metrics", "err", err) + _ = level.Error(logger).Log("msg", "failed collecting license metrics", "err", err) return err } return nil diff --git a/pkg/collector/logical_disk/logical_disk.go b/pkg/collector/logical_disk/logical_disk.go index 4a8b3502d..6e86c61a7 100644 --- a/pkg/collector/logical_disk/logical_disk.go +++ b/pkg/collector/logical_disk/logical_disk.go @@ -34,7 +34,6 @@ var ConfigDefaults = Config{ // A Collector is a Prometheus Collector for perflib logicalDisk metrics. type Collector struct { config Config - logger log.Logger avgReadQueue *prometheus.Desc avgWriteQueue *prometheus.Desc @@ -64,7 +63,7 @@ type volumeInfo struct { readonly float64 } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -81,8 +80,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -126,11 +123,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{"LogicalDisk"}, nil } @@ -138,7 +131,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.information = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "info"), "A metric with a constant '1' value labeled with logical disk information", @@ -268,9 +261,10 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collect(ctx, ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting logical_disk metrics", "err", err) +func (c *Collector) Collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collect(ctx, logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting logical_disk metrics", "err", err) return err } return nil @@ -299,7 +293,8 @@ type logicalDisk struct { AvgDiskSecPerTransfer float64 `perflib:"Avg. Disk sec/Transfer"` } -func (c *Collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var ( err error diskID string @@ -307,7 +302,7 @@ func (c *Collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metri dst []logicalDisk ) - if err = perflib.UnmarshalObject(ctx.PerfObjects["LogicalDisk"], &dst, c.logger); err != nil { + if err = perflib.UnmarshalObject(ctx.PerfObjects["LogicalDisk"], &dst, logger); err != nil { return err } @@ -320,12 +315,12 @@ func (c *Collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metri diskID, err = getDiskIDByVolume(volume.Name) if err != nil { - _ = level.Warn(c.logger).Log("msg", "failed to get disk ID for "+volume.Name, "err", err) + _ = level.Warn(logger).Log("msg", "failed to get disk ID for "+volume.Name, "err", err) } info, err = getVolumeInfo(volume.Name) if err != nil { - _ = level.Warn(c.logger).Log("msg", "failed to get volume information for %s"+volume.Name, "err", err) + _ = level.Warn(logger).Log("msg", "failed to get volume information for %s"+volume.Name, "err", err) } ch <- prometheus.MustNewConstMetric( diff --git a/pkg/collector/logon/logon.go b/pkg/collector/logon/logon.go index fe3617652..e8e9258ec 100644 --- a/pkg/collector/logon/logon.go +++ b/pkg/collector/logon/logon.go @@ -22,12 +22,11 @@ var ConfigDefaults = Config{} // A Collector is a Prometheus Collector for WMI metrics. type Collector struct { config Config - logger log.Logger logonType *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -36,8 +35,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -49,11 +46,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{}, nil } @@ -61,7 +54,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.logonType = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "logon_type"), "Number of active logon sessions (LogonSession.LogonType)", @@ -73,9 +66,10 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collect(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting user metrics", "err", err) +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collect(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting user metrics", "err", err) return err } return nil @@ -87,9 +81,9 @@ type Win32_LogonSession struct { LogonType uint32 } -func (c *Collector) collect(ch chan<- prometheus.Metric) error { +func (c *Collector) collect(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []Win32_LogonSession - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } diff --git a/pkg/collector/memory/memory.go b/pkg/collector/memory/memory.go index 33e3ff737..ca9d6bbfe 100644 --- a/pkg/collector/memory/memory.go +++ b/pkg/collector/memory/memory.go @@ -23,7 +23,6 @@ var ConfigDefaults = Config{} // A Collector is a Prometheus Collector for perflib Memory metrics. type Collector struct { config Config - logger log.Logger availableBytes *prometheus.Desc cacheBytes *prometheus.Desc @@ -59,7 +58,7 @@ type Collector struct { writeCopiesTotal *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -68,8 +67,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -81,11 +78,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{"Memory"}, nil } @@ -93,7 +86,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.availableBytes = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "available_bytes"), "The amount of physical memory immediately available for allocation to a process or for system use. It is equal to the sum of memory assigned to"+ @@ -303,9 +296,10 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collect(ctx, ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting memory metrics", "err", err) +func (c *Collector) Collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collect(ctx, logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting memory metrics", "err", err) return err } return nil @@ -348,9 +342,10 @@ type memory struct { WriteCopiesPersec float64 `perflib:"Write Copies/sec"` } -func (c *Collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var dst []memory - if err := perflib.UnmarshalObject(ctx.PerfObjects["Memory"], &dst, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["Memory"], &dst, logger); err != nil { return err } diff --git a/pkg/collector/mscluster_cluster/mscluster_cluster.go b/pkg/collector/mscluster_cluster/mscluster_cluster.go index 519017200..159b9b7e2 100644 --- a/pkg/collector/mscluster_cluster/mscluster_cluster.go +++ b/pkg/collector/mscluster_cluster/mscluster_cluster.go @@ -17,7 +17,6 @@ var ConfigDefaults = Config{} // A Collector is a Prometheus Collector for WMI MSCluster_Cluster metrics. type Collector struct { config Config - logger log.Logger addEvictDelay *prometheus.Desc adminAccessPoint *prometheus.Desc @@ -98,7 +97,7 @@ type Collector struct { witnessRestartInterval *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -107,8 +106,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -120,11 +117,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{"Memory"}, nil } @@ -132,7 +125,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.addEvictDelay = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "add_evict_delay"), "Provides access to the cluster's AddEvictDelay property, which is the number a seconds that a new node is delayed after an eviction of another node.", @@ -684,9 +677,10 @@ type MSCluster_Cluster struct { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var dst []MSCluster_Cluster - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.QueryNamespace(q, &dst, "root/MSCluster"); err != nil { return err } diff --git a/pkg/collector/mscluster_network/mscluster_network.go b/pkg/collector/mscluster_network/mscluster_network.go index b0726d9da..e9cbae7a6 100644 --- a/pkg/collector/mscluster_network/mscluster_network.go +++ b/pkg/collector/mscluster_network/mscluster_network.go @@ -17,7 +17,6 @@ var ConfigDefaults = Config{} // A Collector is a Prometheus Collector for WMI MSCluster_Network metrics. type Collector struct { config Config - logger log.Logger characteristics *prometheus.Desc flags *prometheus.Desc @@ -26,7 +25,7 @@ type Collector struct { state *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -35,8 +34,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -48,11 +45,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{"Memory"}, nil } @@ -60,7 +53,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.characteristics = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "characteristics"), "Provides the characteristics of the network.", @@ -108,9 +101,10 @@ type MSCluster_Network struct { // Collect sends the metric values for each metric // to the provided prometheus metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var dst []MSCluster_Network - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.QueryNamespace(q, &dst, "root/MSCluster"); err != nil { return err } diff --git a/pkg/collector/mscluster_node/mscluster_node.go b/pkg/collector/mscluster_node/mscluster_node.go index b3a8a4cee..8a7827ed6 100644 --- a/pkg/collector/mscluster_node/mscluster_node.go +++ b/pkg/collector/mscluster_node/mscluster_node.go @@ -20,7 +20,6 @@ var NodeName []string // A Collector is a Prometheus Collector for WMI MSCluster_Node metrics. type Collector struct { config Config - logger log.Logger buildNumber *prometheus.Desc characteristics *prometheus.Desc @@ -38,7 +37,7 @@ type Collector struct { statusInformation *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -47,8 +46,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -60,11 +57,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{"Memory"}, nil } @@ -72,7 +65,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.buildNumber = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "build_number"), "Provides access to the node's BuildNumber property.", @@ -183,9 +176,10 @@ type MSCluster_Node struct { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var dst []MSCluster_Node - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.QueryNamespace(q, &dst, "root/MSCluster"); err != nil { return err } diff --git a/pkg/collector/mscluster_resource/mscluster_resource.go b/pkg/collector/mscluster_resource/mscluster_resource.go index 5f59a3f64..3236490e8 100644 --- a/pkg/collector/mscluster_resource/mscluster_resource.go +++ b/pkg/collector/mscluster_resource/mscluster_resource.go @@ -18,7 +18,6 @@ var ConfigDefaults = Config{} // A Collector is a Prometheus Collector for WMI MSCluster_Resource metrics. type Collector struct { config Config - logger log.Logger characteristics *prometheus.Desc deadlockTimeout *prometheus.Desc @@ -39,7 +38,7 @@ type Collector struct { subclass *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -48,8 +47,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -61,11 +58,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{"Memory"}, nil } @@ -73,7 +66,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.characteristics = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "characteristics"), "Provides the characteristics of the object.", @@ -213,9 +206,10 @@ type MSCluster_Resource struct { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var dst []MSCluster_Resource - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.QueryNamespace(q, &dst, "root/MSCluster"); err != nil { return err } diff --git a/pkg/collector/mscluster_resourcegroup/mscluster_resourcegroup.go b/pkg/collector/mscluster_resourcegroup/mscluster_resourcegroup.go index b1810e878..f85a53221 100644 --- a/pkg/collector/mscluster_resourcegroup/mscluster_resourcegroup.go +++ b/pkg/collector/mscluster_resourcegroup/mscluster_resourcegroup.go @@ -18,7 +18,6 @@ var ConfigDefaults = Config{} // A Collector is a Prometheus Collector for WMI MSCluster_ResourceGroup metrics. type Collector struct { config Config - logger log.Logger autoFailbackType *prometheus.Desc characteristics *prometheus.Desc @@ -36,7 +35,7 @@ type Collector struct { state *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -45,8 +44,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -58,11 +55,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{"Memory"}, nil } @@ -70,7 +63,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.autoFailbackType = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "auto_failback_type"), "Provides access to the group's AutoFailbackType property.", @@ -187,9 +180,10 @@ type MSCluster_ResourceGroup struct { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var dst []MSCluster_ResourceGroup - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.QueryNamespace(q, &dst, "root/MSCluster"); err != nil { return err } diff --git a/pkg/collector/msmq/msmq.go b/pkg/collector/msmq/msmq.go index 66bbf7221..74e7a1674 100644 --- a/pkg/collector/msmq/msmq.go +++ b/pkg/collector/msmq/msmq.go @@ -27,7 +27,6 @@ var ConfigDefaults = Config{ // A Collector is a Prometheus Collector for WMI Win32_PerfRawData_MSMQ_MSMQQueue metrics. type Collector struct { config Config - logger log.Logger bytesInJournalQueue *prometheus.Desc bytesInQueue *prometheus.Desc @@ -35,7 +34,7 @@ type Collector struct { messagesInQueue *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -48,8 +47,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -69,11 +66,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{}, nil } @@ -81,9 +74,11 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(logger log.Logger) error { + logger = log.With(logger, "collector", Name) + if *c.config.QueryWhereClause == "" { - _ = level.Warn(c.logger).Log("msg", "No where-clause specified for msmq collector. This will generate a very large number of metrics!") + _ = level.Warn(logger).Log("msg", "No where-clause specified for msmq collector. This will generate a very large number of metrics!") } c.bytesInJournalQueue = prometheus.NewDesc( @@ -115,9 +110,10 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collect(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting msmq metrics", "err", err) +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collect(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting msmq metrics", "err", err) return err } return nil @@ -132,10 +128,10 @@ type msmqQueue struct { MessagesInQueue uint64 } -func (c *Collector) collect(ch chan<- prometheus.Metric) error { +func (c *Collector) collect(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []msmqQueue - q := wmi.QueryAllForClassWhere(&dst, "Win32_PerfRawData_MSMQ_MSMQQueue", *c.config.QueryWhereClause, c.logger) + q := wmi.QueryAllForClassWhere(&dst, "Win32_PerfRawData_MSMQ_MSMQQueue", *c.config.QueryWhereClause, logger) if err := wmi.Query(q, &dst); err != nil { return err } diff --git a/pkg/collector/mssql/mssql.go b/pkg/collector/mssql/mssql.go index 027e87673..580acbef2 100644 --- a/pkg/collector/mssql/mssql.go +++ b/pkg/collector/mssql/mssql.go @@ -142,7 +142,6 @@ func mssqlGetPerfObjectName(sqlInstance string, collector string) string { // A Collector is a Prometheus Collector for various WMI Win32_PerfRawData_MSSQLSERVER_* metrics. type Collector struct { config Config - logger log.Logger // meta mssqlScrapeDurationDesc *prometheus.Desc @@ -414,7 +413,7 @@ type Collector struct { mssqlChildCollectorFailure int } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -427,8 +426,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -480,12 +477,8 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { - c.mssqlInstances = getMSSQLInstances(c.logger) +func (c *Collector) GetPerfCounter(logger log.Logger) ([]string, error) { + c.mssqlInstances = getMSSQLInstances(logger) perfCounters := make([]string, 0, len(c.mssqlInstances)*len(c.config.CollectorsEnabled)) for instance := range c.mssqlInstances { @@ -501,7 +494,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { // Result must order, to prevent test failures. sort.Strings(c.config.CollectorsEnabled) @@ -1977,24 +1970,24 @@ func (c *Collector) Build() error { return nil } -type mssqlCollectorFunc func(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error +type mssqlCollectorFunc func(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric, sqlInstance string) error -func (c *Collector) execute(ctx *types.ScrapeContext, name string, fn mssqlCollectorFunc, ch chan<- prometheus.Metric, sqlInstance string, wg *sync.WaitGroup) { +func (c *Collector) execute(ctx *types.ScrapeContext, logger log.Logger, name string, fn mssqlCollectorFunc, ch chan<- prometheus.Metric, sqlInstance string, wg *sync.WaitGroup) { // Reset failure counter on each scrape c.mssqlChildCollectorFailure = 0 defer wg.Done() begin := time.Now() - err := fn(ctx, ch, sqlInstance) + err := fn(ctx, logger, ch, sqlInstance) duration := time.Since(begin) var success float64 if err != nil { - _ = level.Error(c.logger).Log("msg", fmt.Sprintf("mssql class collector %s failed after %fs", name, duration.Seconds()), "err", err) + _ = level.Error(logger).Log("msg", fmt.Sprintf("mssql class collector %s failed after %fs", name, duration.Seconds()), "err", err) success = 0 c.mssqlChildCollectorFailure++ } else { - _ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql class collector %s succeeded after %fs.", name, duration.Seconds())) + _ = level.Debug(logger).Log("msg", fmt.Sprintf("mssql class collector %s succeeded after %fs.", name, duration.Seconds())) success = 1 } ch <- prometheus.MustNewConstMetric( @@ -2013,7 +2006,8 @@ func (c *Collector) execute(ctx *types.ScrapeContext, name string, fn mssqlColle // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) Collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) wg := sync.WaitGroup{} for sqlInstance := range c.mssqlInstances { @@ -2021,7 +2015,7 @@ func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metri function := c.mssqlCollectors[name] wg.Add(1) - go c.execute(ctx, name, function, ch, sqlInstance, &wg) + go c.execute(ctx, logger, name, function, ch, sqlInstance, &wg) } } @@ -2084,11 +2078,11 @@ type mssqlAccessMethods struct { WorktablesFromCacheRatioBase float64 `perflib:"Worktables From Cache Base_Base"` } -func (c *Collector) collectAccessMethods(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error { +func (c *Collector) collectAccessMethods(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric, sqlInstance string) error { var dst []mssqlAccessMethods - _ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_accessmethods collector iterating sql instance %s.", sqlInstance)) + _ = level.Debug(logger).Log("msg", fmt.Sprintf("mssql_accessmethods collector iterating sql instance %s.", sqlInstance)) - if err := perflib.UnmarshalObject(ctx.PerfObjects[mssqlGetPerfObjectName(sqlInstance, "accessmethods")], &dst, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects[mssqlGetPerfObjectName(sqlInstance, "accessmethods")], &dst, logger); err != nil { return err } @@ -2419,11 +2413,11 @@ type mssqlAvailabilityReplica struct { SendstoTransportPerSec float64 `perflib:"Sends to Transport/sec"` } -func (c *Collector) collectAvailabilityReplica(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error { +func (c *Collector) collectAvailabilityReplica(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric, sqlInstance string) error { var dst []mssqlAvailabilityReplica - _ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_availreplica collector iterating sql instance %s.", sqlInstance)) + _ = level.Debug(logger).Log("msg", fmt.Sprintf("mssql_availreplica collector iterating sql instance %s.", sqlInstance)) - if err := perflib.UnmarshalObject(ctx.PerfObjects[mssqlGetPerfObjectName(sqlInstance, "availreplica")], &dst, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects[mssqlGetPerfObjectName(sqlInstance, "availreplica")], &dst, logger); err != nil { return err } @@ -2527,11 +2521,11 @@ type mssqlBufferManager struct { TargetPages float64 `perflib:"Target pages"` } -func (c *Collector) collectBufferManager(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error { +func (c *Collector) collectBufferManager(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric, sqlInstance string) error { var dst []mssqlBufferManager - _ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_bufman collector iterating sql instance %s.", sqlInstance)) + _ = level.Debug(logger).Log("msg", fmt.Sprintf("mssql_bufman collector iterating sql instance %s.", sqlInstance)) - if err := perflib.UnmarshalObject(ctx.PerfObjects[mssqlGetPerfObjectName(sqlInstance, "bufman")], &dst, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects[mssqlGetPerfObjectName(sqlInstance, "bufman")], &dst, logger); err != nil { return err } @@ -2731,11 +2725,11 @@ type mssqlDatabaseReplica struct { TransactionDelay float64 `perflib:"Transaction Delay"` } -func (c *Collector) collectDatabaseReplica(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error { +func (c *Collector) collectDatabaseReplica(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric, sqlInstance string) error { var dst []mssqlDatabaseReplica - _ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_dbreplica collector iterating sql instance %s.", sqlInstance)) + _ = level.Debug(logger).Log("msg", fmt.Sprintf("mssql_dbreplica collector iterating sql instance %s.", sqlInstance)) - if err := perflib.UnmarshalObject(ctx.PerfObjects[mssqlGetPerfObjectName(sqlInstance, "dbreplica")], &dst, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects[mssqlGetPerfObjectName(sqlInstance, "dbreplica")], &dst, logger); err != nil { return err } @@ -2970,11 +2964,11 @@ type mssqlDatabases struct { XTPMemoryUsedKB float64 `perflib:"XTP Memory Used (KB)"` } -func (c *Collector) collectDatabases(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error { +func (c *Collector) collectDatabases(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric, sqlInstance string) error { var dst []mssqlDatabases - _ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_databases collector iterating sql instance %s.", sqlInstance)) + _ = level.Debug(logger).Log("msg", fmt.Sprintf("mssql_databases collector iterating sql instance %s.", sqlInstance)) - if err := perflib.UnmarshalObject(ctx.PerfObjects[mssqlGetPerfObjectName(sqlInstance, "databases")], &dst, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects[mssqlGetPerfObjectName(sqlInstance, "databases")], &dst, logger); err != nil { return err } @@ -3352,11 +3346,11 @@ type mssqlGeneralStatistics struct { UserConnections float64 `perflib:"User Connections"` } -func (c *Collector) collectGeneralStatistics(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error { +func (c *Collector) collectGeneralStatistics(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric, sqlInstance string) error { var dst []mssqlGeneralStatistics - _ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_genstats collector iterating sql instance %s.", sqlInstance)) + _ = level.Debug(logger).Log("msg", fmt.Sprintf("mssql_genstats collector iterating sql instance %s.", sqlInstance)) - if err := perflib.UnmarshalObject(ctx.PerfObjects[mssqlGetPerfObjectName(sqlInstance, "genstats")], &dst, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects[mssqlGetPerfObjectName(sqlInstance, "genstats")], &dst, logger); err != nil { return err } @@ -3547,11 +3541,11 @@ type mssqlLocks struct { NumberOfDeadlocksPerSec float64 `perflib:"Number of Deadlocks/sec"` } -func (c *Collector) collectLocks(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error { +func (c *Collector) collectLocks(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric, sqlInstance string) error { var dst []mssqlLocks - _ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_locks collector iterating sql instance %s.", sqlInstance)) + _ = level.Debug(logger).Log("msg", fmt.Sprintf("mssql_locks collector iterating sql instance %s.", sqlInstance)) - if err := perflib.UnmarshalObject(ctx.PerfObjects[mssqlGetPerfObjectName(sqlInstance, "locks")], &dst, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects[mssqlGetPerfObjectName(sqlInstance, "locks")], &dst, logger); err != nil { return err } @@ -3645,11 +3639,11 @@ type mssqlMemoryManager struct { TotalServerMemoryKB float64 `perflib:"Total Server Memory (KB)"` } -func (c *Collector) collectMemoryManager(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error { +func (c *Collector) collectMemoryManager(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric, sqlInstance string) error { var dst []mssqlMemoryManager - _ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_memmgr collector iterating sql instance %s.", sqlInstance)) + _ = level.Debug(logger).Log("msg", fmt.Sprintf("mssql_memmgr collector iterating sql instance %s.", sqlInstance)) - if err := perflib.UnmarshalObject(ctx.PerfObjects[mssqlGetPerfObjectName(sqlInstance, "memmgr")], &dst, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects[mssqlGetPerfObjectName(sqlInstance, "memmgr")], &dst, logger); err != nil { return err } @@ -3814,11 +3808,11 @@ type mssqlSQLStatistics struct { UnsafeAutoParamsPerSec float64 `perflib:"Unsafe Auto-Params/sec"` } -func (c *Collector) collectSQLStats(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error { +func (c *Collector) collectSQLStats(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric, sqlInstance string) error { var dst []mssqlSQLStatistics - _ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_sqlstats collector iterating sql instance %s.", sqlInstance)) + _ = level.Debug(logger).Log("msg", fmt.Sprintf("mssql_sqlstats collector iterating sql instance %s.", sqlInstance)) - if err := perflib.UnmarshalObject(ctx.PerfObjects[mssqlGetPerfObjectName(sqlInstance, "sqlstats")], &dst, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects[mssqlGetPerfObjectName(sqlInstance, "sqlstats")], &dst, logger); err != nil { return err } @@ -3922,11 +3916,11 @@ type mssqlWaitStatistics struct { WaitStatsTransactionOwnershipWaits float64 `perflib:"Transaction ownership waits"` } -func (c *Collector) collectWaitStats(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error { +func (c *Collector) collectWaitStats(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric, sqlInstance string) error { var dst []mssqlWaitStatistics - _ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_waitstats collector iterating sql instance %s.", sqlInstance)) + _ = level.Debug(logger).Log("msg", fmt.Sprintf("mssql_waitstats collector iterating sql instance %s.", sqlInstance)) - if err := perflib.UnmarshalObject(ctx.PerfObjects[mssqlGetPerfObjectName(sqlInstance, "waitstats")], &dst, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects[mssqlGetPerfObjectName(sqlInstance, "waitstats")], &dst, logger); err != nil { return err } @@ -4028,11 +4022,11 @@ type mssqlSQLErrors struct { // Win32_PerfRawData_MSSQLSERVER_SQLServerErrors docs: // - https://docs.microsoft.com/en-us/sql/relational-databases/performance-monitor/sql-server-sql-errors-object -func (c *Collector) collectSQLErrors(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error { +func (c *Collector) collectSQLErrors(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric, sqlInstance string) error { var dst []mssqlSQLErrors - _ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_sqlerrors collector iterating sql instance %s.", sqlInstance)) + _ = level.Debug(logger).Log("msg", fmt.Sprintf("mssql_sqlerrors collector iterating sql instance %s.", sqlInstance)) - if err := perflib.UnmarshalObject(ctx.PerfObjects[mssqlGetPerfObjectName(sqlInstance, "sqlerrors")], &dst, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects[mssqlGetPerfObjectName(sqlInstance, "sqlerrors")], &dst, logger); err != nil { return err } @@ -4071,11 +4065,11 @@ type mssqlTransactions struct { // Win32_PerfRawData_MSSQLSERVER_Transactions docs: // - https://docs.microsoft.com/en-us/sql/relational-databases/performance-monitor/sql-server-transactions-object -func (c *Collector) collectTransactions(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error { +func (c *Collector) collectTransactions(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric, sqlInstance string) error { var dst []mssqlTransactions - _ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_transactions collector iterating sql instance %s.", sqlInstance)) + _ = level.Debug(logger).Log("msg", fmt.Sprintf("mssql_transactions collector iterating sql instance %s.", sqlInstance)) - if err := perflib.UnmarshalObject(ctx.PerfObjects[mssqlGetPerfObjectName(sqlInstance, "transactions")], &dst, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects[mssqlGetPerfObjectName(sqlInstance, "transactions")], &dst, logger); err != nil { return err } diff --git a/pkg/collector/net/net.go b/pkg/collector/net/net.go index 7721deae2..9aa7f0507 100644 --- a/pkg/collector/net/net.go +++ b/pkg/collector/net/net.go @@ -31,7 +31,6 @@ var nicNameToUnderscore = regexp.MustCompile("[^a-zA-Z0-9]") // A Collector is a Prometheus Collector for Perflib Network Interface metrics. type Collector struct { config Config - logger log.Logger bytesReceivedTotal *prometheus.Desc bytesSentTotal *prometheus.Desc @@ -48,7 +47,7 @@ type Collector struct { currentBandwidth *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -65,8 +64,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -110,11 +107,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{"Network Interface"}, nil } @@ -122,7 +115,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.bytesReceivedTotal = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "bytes_received_total"), "(Network.BytesReceivedPerSec)", @@ -207,9 +200,10 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collect(ctx, ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting net metrics", "err", err) +func (c *Collector) Collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collect(ctx, logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting net metrics", "err", err) return err } return nil @@ -240,10 +234,11 @@ type networkInterface struct { CurrentBandwidth float64 `perflib:"Current Bandwidth"` } -func (c *Collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var dst []networkInterface - if err := perflib.UnmarshalObject(ctx.PerfObjects["Network Interface"], &dst, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["Network Interface"], &dst, logger); err != nil { return err } diff --git a/pkg/collector/netframework_clrexceptions/netframework_clrexceptions.go b/pkg/collector/netframework_clrexceptions/netframework_clrexceptions.go index d2049a5cd..1e9933d26 100644 --- a/pkg/collector/netframework_clrexceptions/netframework_clrexceptions.go +++ b/pkg/collector/netframework_clrexceptions/netframework_clrexceptions.go @@ -20,7 +20,6 @@ var ConfigDefaults = Config{} // A Collector is a Prometheus Collector for WMI Win32_PerfRawData_NETFramework_NETCLRExceptions metrics. type Collector struct { config Config - logger log.Logger numberOfExceptionsThrown *prometheus.Desc numberOfFilters *prometheus.Desc @@ -28,7 +27,7 @@ type Collector struct { throwToCatchDepth *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -37,8 +36,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -50,11 +47,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{}, nil } @@ -62,7 +55,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.numberOfExceptionsThrown = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "exceptions_thrown_total"), "Displays the total number of exceptions thrown since the application started. This includes both .NET exceptions and unmanaged exceptions that are converted into .NET exceptions.", @@ -92,9 +85,10 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collect(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrexceptions metrics", "err", err) +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collect(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrexceptions metrics", "err", err) return err } return nil @@ -110,9 +104,9 @@ type Win32_PerfRawData_NETFramework_NETCLRExceptions struct { ThrowToCatchDepthPersec uint32 } -func (c *Collector) collect(ch chan<- prometheus.Metric) error { +func (c *Collector) collect(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []Win32_PerfRawData_NETFramework_NETCLRExceptions - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } diff --git a/pkg/collector/netframework_clrinterop/netframework_clrinterop.go b/pkg/collector/netframework_clrinterop/netframework_clrinterop.go index 74333b3ce..bec6f6af7 100644 --- a/pkg/collector/netframework_clrinterop/netframework_clrinterop.go +++ b/pkg/collector/netframework_clrinterop/netframework_clrinterop.go @@ -20,14 +20,13 @@ var ConfigDefaults = Config{} // A Collector is a Prometheus Collector for WMI Win32_PerfRawData_NETFramework_NETCLRInterop metrics. type Collector struct { config Config - logger log.Logger numberOfCCWs *prometheus.Desc numberOfMarshalling *prometheus.Desc numberOfStubs *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -36,8 +35,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -49,11 +46,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{}, nil } @@ -61,7 +54,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.numberOfCCWs = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "com_callable_wrappers_total"), "Displays the current number of COM callable wrappers (CCWs). A CCW is a proxy for a managed object being referenced from an unmanaged COM client.", @@ -85,9 +78,10 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collect(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrinterop metrics", "err", err) +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collect(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrinterop metrics", "err", err) return err } return nil @@ -103,9 +97,9 @@ type Win32_PerfRawData_NETFramework_NETCLRInterop struct { NumberofTLBimportsPersec uint32 } -func (c *Collector) collect(ch chan<- prometheus.Metric) error { +func (c *Collector) collect(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []Win32_PerfRawData_NETFramework_NETCLRInterop - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } diff --git a/pkg/collector/netframework_clrjit/netframework_clrjit.go b/pkg/collector/netframework_clrjit/netframework_clrjit.go index 01cb5d91c..2ee83c5e7 100644 --- a/pkg/collector/netframework_clrjit/netframework_clrjit.go +++ b/pkg/collector/netframework_clrjit/netframework_clrjit.go @@ -20,7 +20,6 @@ var ConfigDefaults = Config{} // A Collector is a Prometheus Collector for WMI Win32_PerfRawData_NETFramework_NETCLRJit metrics. type Collector struct { config Config - logger log.Logger numberOfMethodsJitted *prometheus.Desc timeInJit *prometheus.Desc @@ -28,7 +27,7 @@ type Collector struct { totalNumberOfILBytesJitted *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -37,8 +36,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -50,11 +47,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{}, nil } @@ -62,7 +55,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.numberOfMethodsJitted = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "jit_methods_total"), "Displays the total number of methods JIT-compiled since the application started. This counter does not include pre-JIT-compiled methods.", @@ -92,9 +85,10 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collect(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrjit metrics", "err", err) +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collect(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrjit metrics", "err", err) return err } return nil @@ -112,9 +106,9 @@ type Win32_PerfRawData_NETFramework_NETCLRJit struct { TotalNumberofILBytesJitted uint32 } -func (c *Collector) collect(ch chan<- prometheus.Metric) error { +func (c *Collector) collect(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []Win32_PerfRawData_NETFramework_NETCLRJit - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } diff --git a/pkg/collector/netframework_clrloading/netframework_clrloading.go b/pkg/collector/netframework_clrloading/netframework_clrloading.go index 58ef6b5d0..a1d2de064 100644 --- a/pkg/collector/netframework_clrloading/netframework_clrloading.go +++ b/pkg/collector/netframework_clrloading/netframework_clrloading.go @@ -20,7 +20,6 @@ var ConfigDefaults = Config{} // A Collector is a Prometheus Collector for WMI Win32_PerfRawData_NETFramework_NETCLRLoading metrics. type Collector struct { config Config - logger log.Logger bytesInLoaderHeap *prometheus.Desc currentAppDomains *prometheus.Desc @@ -33,7 +32,7 @@ type Collector struct { totalNumberOfLoadFailures *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -42,8 +41,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -55,11 +52,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{}, nil } @@ -67,7 +60,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.bytesInLoaderHeap = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "loader_heap_size_bytes"), "Displays the current size, in bytes, of the memory committed by the class loader across all application domains. Committed memory is the physical space reserved in the disk paging file.", @@ -127,9 +120,10 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collect(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrloading metrics", "err", err) +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collect(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrloading metrics", "err", err) return err } return nil @@ -156,9 +150,9 @@ type Win32_PerfRawData_NETFramework_NETCLRLoading struct { TotalNumberofLoadFailures uint32 } -func (c *Collector) collect(ch chan<- prometheus.Metric) error { +func (c *Collector) collect(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []Win32_PerfRawData_NETFramework_NETCLRLoading - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } diff --git a/pkg/collector/netframework_clrlocksandthreads/netframework_clrlocksandthreads.go b/pkg/collector/netframework_clrlocksandthreads/netframework_clrlocksandthreads.go index bef9b41b4..1a96e067a 100644 --- a/pkg/collector/netframework_clrlocksandthreads/netframework_clrlocksandthreads.go +++ b/pkg/collector/netframework_clrlocksandthreads/netframework_clrlocksandthreads.go @@ -20,7 +20,6 @@ var ConfigDefaults = Config{} // A Collector is a Prometheus Collector for WMI Win32_PerfRawData_NETFramework_NETCLRLocksAndThreads metrics. type Collector struct { config Config - logger log.Logger currentQueueLength *prometheus.Desc numberOfCurrentLogicalThreads *prometheus.Desc @@ -31,7 +30,7 @@ type Collector struct { totalNumberOfContentions *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -40,8 +39,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -53,11 +50,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{}, nil } @@ -65,7 +58,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.currentQueueLength = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "current_queue_length"), "Displays the total number of threads that are currently waiting to acquire a managed lock in the application.", @@ -113,9 +106,10 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collect(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrlocksandthreads metrics", "err", err) +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collect(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrlocksandthreads metrics", "err", err) return err } return nil @@ -136,9 +130,9 @@ type Win32_PerfRawData_NETFramework_NETCLRLocksAndThreads struct { TotalNumberofContentions uint32 } -func (c *Collector) collect(ch chan<- prometheus.Metric) error { +func (c *Collector) collect(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []Win32_PerfRawData_NETFramework_NETCLRLocksAndThreads - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } diff --git a/pkg/collector/netframework_clrmemory/netframework_clrmemory.go b/pkg/collector/netframework_clrmemory/netframework_clrmemory.go index 4602ec16a..5a3932c85 100644 --- a/pkg/collector/netframework_clrmemory/netframework_clrmemory.go +++ b/pkg/collector/netframework_clrmemory/netframework_clrmemory.go @@ -20,7 +20,6 @@ var ConfigDefaults = Config{} // A Collector is a Prometheus Collector for WMI Win32_PerfRawData_NETFramework_NETCLRMemory metrics. type Collector struct { config Config - logger log.Logger allocatedBytes *prometheus.Desc finalizationSurvivors *prometheus.Desc @@ -36,7 +35,7 @@ type Collector struct { timeInGC *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -45,8 +44,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -58,11 +55,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{}, nil } @@ -70,7 +63,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.allocatedBytes = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "allocated_bytes_total"), "Displays the total number of bytes allocated on the garbage collection heap.", @@ -148,9 +141,10 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collect(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrmemory metrics", "err", err) +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collect(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrmemory metrics", "err", err) return err } return nil @@ -190,9 +184,9 @@ type Win32_PerfRawData_NETFramework_NETCLRMemory struct { PromotedMemoryfromGen1 uint64 } -func (c *Collector) collect(ch chan<- prometheus.Metric) error { +func (c *Collector) collect(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []Win32_PerfRawData_NETFramework_NETCLRMemory - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } diff --git a/pkg/collector/netframework_clrremoting/netframework_clrremoting.go b/pkg/collector/netframework_clrremoting/netframework_clrremoting.go index 9f803162a..b81799077 100644 --- a/pkg/collector/netframework_clrremoting/netframework_clrremoting.go +++ b/pkg/collector/netframework_clrremoting/netframework_clrremoting.go @@ -20,7 +20,6 @@ var ConfigDefaults = Config{} // A Collector is a Prometheus Collector for WMI Win32_PerfRawData_NETFramework_NETCLRRemoting metrics. type Collector struct { config Config - logger log.Logger channels *prometheus.Desc contextBoundClassesLoaded *prometheus.Desc @@ -30,7 +29,7 @@ type Collector struct { totalRemoteCalls *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -39,8 +38,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -52,11 +49,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{}, nil } @@ -64,7 +57,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.channels = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "channels_total"), "Displays the total number of remoting channels registered across all application domains since application started.", @@ -106,9 +99,10 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collect(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrremoting metrics", "err", err) +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collect(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrremoting metrics", "err", err) return err } return nil @@ -126,9 +120,9 @@ type Win32_PerfRawData_NETFramework_NETCLRRemoting struct { TotalRemoteCalls uint32 } -func (c *Collector) collect(ch chan<- prometheus.Metric) error { +func (c *Collector) collect(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []Win32_PerfRawData_NETFramework_NETCLRRemoting - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } diff --git a/pkg/collector/netframework_clrsecurity/netframework_clrsecurity.go b/pkg/collector/netframework_clrsecurity/netframework_clrsecurity.go index c66bd4bd6..46369057c 100644 --- a/pkg/collector/netframework_clrsecurity/netframework_clrsecurity.go +++ b/pkg/collector/netframework_clrsecurity/netframework_clrsecurity.go @@ -20,7 +20,6 @@ var ConfigDefaults = Config{} // A Collector is a Prometheus Collector for WMI Win32_PerfRawData_NETFramework_NETCLRSecurity metrics. type Collector struct { config Config - logger log.Logger numberLinkTimeChecks *prometheus.Desc timeInRTChecks *prometheus.Desc @@ -28,7 +27,7 @@ type Collector struct { totalRuntimeChecks *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -37,8 +36,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -50,11 +47,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{}, nil } @@ -62,7 +55,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.numberLinkTimeChecks = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "link_time_checks_total"), "Displays the total number of link-time code access security checks since the application started.", @@ -92,9 +85,10 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collect(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrsecurity metrics", "err", err) +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collect(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrsecurity metrics", "err", err) return err } return nil @@ -111,9 +105,9 @@ type Win32_PerfRawData_NETFramework_NETCLRSecurity struct { TotalRuntimeChecks uint32 } -func (c *Collector) collect(ch chan<- prometheus.Metric) error { +func (c *Collector) collect(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []Win32_PerfRawData_NETFramework_NETCLRSecurity - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } diff --git a/pkg/collector/nps/nps.go b/pkg/collector/nps/nps.go index 170583b63..002aee121 100644 --- a/pkg/collector/nps/nps.go +++ b/pkg/collector/nps/nps.go @@ -20,7 +20,6 @@ var ConfigDefaults = Config{} // Collector is a Prometheus Collector for WMI Win32_PerfRawData_IAS_NPSAuthenticationServer and Win32_PerfRawData_IAS_NPSAccountingServer metrics. type Collector struct { config Config - logger log.Logger accessAccepts *prometheus.Desc accessChallenges *prometheus.Desc @@ -50,7 +49,7 @@ type Collector struct { accountingUnknownType *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -59,8 +58,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -72,11 +69,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{}, nil } @@ -84,7 +77,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.accessAccepts = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "access_accepts"), "(AccessAccepts)", @@ -241,13 +234,14 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.CollectAccept(ch); err != nil { - _ = level.Error(c.logger).Log("msg", fmt.Sprintf("failed collecting NPS accept data: %s", err)) +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.CollectAccept(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", fmt.Sprintf("failed collecting NPS accept data: %s", err)) return err } - if err := c.CollectAccounting(ch); err != nil { - _ = level.Error(c.logger).Log("msg", fmt.Sprintf("failed collecting NPS accounting data: %s", err)) + if err := c.CollectAccounting(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", fmt.Sprintf("failed collecting NPS accounting data: %s", err)) return err } return nil @@ -292,9 +286,9 @@ type Win32_PerfRawData_IAS_NPSAccountingServer struct { // CollectAccept sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) CollectAccept(ch chan<- prometheus.Metric) error { +func (c *Collector) CollectAccept(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []Win32_PerfRawData_IAS_NPSAuthenticationServer - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } @@ -380,9 +374,9 @@ func (c *Collector) CollectAccept(ch chan<- prometheus.Metric) error { return nil } -func (c *Collector) CollectAccounting(ch chan<- prometheus.Metric) error { +func (c *Collector) CollectAccounting(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []Win32_PerfRawData_IAS_NPSAccountingServer - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } diff --git a/pkg/collector/os/os.go b/pkg/collector/os/os.go index be24fd72d..b6cf064e8 100644 --- a/pkg/collector/os/os.go +++ b/pkg/collector/os/os.go @@ -33,7 +33,6 @@ var ConfigDefaults = Config{} // A Collector is a Prometheus Collector for WMI metrics. type Collector struct { config Config - logger log.Logger osInformation *prometheus.Desc pagingFreeBytes *prometheus.Desc @@ -56,7 +55,7 @@ type pagingFileCounter struct { UsagePeak float64 `perflib:"% Usage Peak"` } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -65,8 +64,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -78,11 +75,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{"Paging File"}, nil } @@ -90,7 +83,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.osInformation = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "info"), "OperatingSystem.Caption, OperatingSystem.Version", @@ -174,9 +167,10 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collect(ctx, ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting os metrics", "err", err) +func (c *Collector) Collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collect(ctx, logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting os metrics", "err", err) return err } return nil @@ -200,7 +194,8 @@ type Win32_OperatingSystem struct { Version string } -func (c *Collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) nwgi, err := netapi32.GetWorkstationInfo() if err != nil { return err @@ -237,7 +232,7 @@ func (c *Collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metri file, err := os.Stat(fileString) // For unknown reasons, Windows doesn't always create a page file. Continue collection rather than aborting. if err != nil { - _ = level.Debug(c.logger).Log("msg", fmt.Sprintf("Failed to read page file (reason: %s): %s\n", err, fileString)) + _ = level.Debug(logger).Log("msg", fmt.Sprintf("Failed to read page file (reason: %s): %s\n", err, fileString)) } else { fsipf += float64(file.Size()) } @@ -274,7 +269,7 @@ func (c *Collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metri } pfc := make([]pagingFileCounter, 0) - if err := perflib.UnmarshalObject(ctx.PerfObjects["Paging File"], &pfc, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["Paging File"], &pfc, logger); err != nil { return err } @@ -334,7 +329,7 @@ func (c *Collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metri fsipf, ) } else { - _ = level.Debug(c.logger).Log("msg", "Could not find HKLM:\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Memory Management key. windows_os_paging_free_bytes and windows_os_paging_limit_bytes will be omitted.") + _ = level.Debug(logger).Log("msg", "Could not find HKLM:\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Memory Management key. windows_os_paging_free_bytes and windows_os_paging_limit_bytes will be omitted.") } ch <- prometheus.MustNewConstMetric( c.virtualMemoryFreeBytes, diff --git a/pkg/collector/physical_disk/physical_disk.go b/pkg/collector/physical_disk/physical_disk.go index 4f55c672e..37d094d7e 100644 --- a/pkg/collector/physical_disk/physical_disk.go +++ b/pkg/collector/physical_disk/physical_disk.go @@ -30,7 +30,6 @@ var ConfigDefaults = Config{ // A Collector is a Prometheus Collector for perflib PhysicalDisk metrics. type Collector struct { config Config - logger log.Logger idleTime *prometheus.Desc readBytesTotal *prometheus.Desc @@ -46,7 +45,7 @@ type Collector struct { writesTotal *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -63,8 +62,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -108,11 +105,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{"PhysicalDisk"}, nil } @@ -120,7 +113,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.requestsQueued = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "requests_queued"), "The number of requests queued to the disk (PhysicalDisk.CurrentDiskQueueLength)", @@ -210,9 +203,10 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collect(ctx, ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting physical_disk metrics", "err", err) +func (c *Collector) Collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collect(ctx, logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting physical_disk metrics", "err", err) return err } return nil @@ -237,9 +231,10 @@ type PhysicalDisk struct { AvgDiskSecPerTransfer float64 `perflib:"Avg. Disk sec/Transfer"` } -func (c *Collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var dst []PhysicalDisk - if err := perflib.UnmarshalObject(ctx.PerfObjects["PhysicalDisk"], &dst, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["PhysicalDisk"], &dst, logger); err != nil { return err } diff --git a/pkg/collector/printer/printer.go b/pkg/collector/printer/printer.go index 2b0350ff5..a9b274a23 100644 --- a/pkg/collector/printer/printer.go +++ b/pkg/collector/printer/printer.go @@ -40,14 +40,13 @@ var ConfigDefaults = Config{ type Collector struct { config Config - logger log.Logger printerStatus *prometheus.Desc printerJobStatus *prometheus.Desc printerJobCount *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -64,8 +63,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -105,15 +102,11 @@ func NewWithFlags(app *kingpin.Application) *Collector { return c } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.printerJobStatus = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "job_status"), "A counter of printer jobs by status", @@ -138,7 +131,7 @@ func (c *Collector) Build() error { func (c *Collector) GetName() string { return Name } -func (c *Collector) GetPerfCounter() ([]string, error) { return []string{"Printer"}, nil } +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{"Printer"}, nil } type wmiPrinter struct { Name string @@ -152,24 +145,25 @@ type wmiPrintJob struct { Status string } -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collectPrinterStatus(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed to collect printer status metrics", "err", err) +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collectPrinterStatus(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed to collect printer status metrics", "err", err) return err } - if err := c.collectPrinterJobStatus(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed to collect printer job status metrics", "err", err) + if err := c.collectPrinterJobStatus(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed to collect printer job status metrics", "err", err) return err } return nil } -func (c *Collector) collectPrinterStatus(ch chan<- prometheus.Metric) error { +func (c *Collector) collectPrinterStatus(logger log.Logger, ch chan<- prometheus.Metric) error { var printers []wmiPrinter - q := wmi.QueryAllForClass(&printers, "win32_Printer", c.logger) + q := wmi.QueryAllForClass(&printers, "win32_Printer", logger) if err := wmi.Query(q, &printers); err != nil { return err } @@ -206,10 +200,10 @@ func (c *Collector) collectPrinterStatus(ch chan<- prometheus.Metric) error { return nil } -func (c *Collector) collectPrinterJobStatus(ch chan<- prometheus.Metric) error { +func (c *Collector) collectPrinterJobStatus(logger log.Logger, ch chan<- prometheus.Metric) error { var printJobs []wmiPrintJob - q := wmi.QueryAllForClass(&printJobs, "win32_PrintJob", c.logger) + q := wmi.QueryAllForClass(&printJobs, "win32_PrintJob", logger) if err := wmi.Query(q, &printJobs); err != nil { return err } diff --git a/pkg/collector/process/process.go b/pkg/collector/process/process.go index fbd9d9949..b7ce22bfd 100644 --- a/pkg/collector/process/process.go +++ b/pkg/collector/process/process.go @@ -38,7 +38,6 @@ var ConfigDefaults = Config{ type Collector struct { config Config - logger log.Logger lookupCache map[string]string @@ -59,7 +58,7 @@ type Collector struct { workingSetPrivate *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -76,8 +75,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -131,11 +128,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{"Process"}, nil } @@ -143,9 +136,11 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(logger log.Logger) error { + logger = log.With(logger, "collector", Name) + if c.config.ProcessInclude.String() == "^(?:.*)$" && c.config.ProcessExclude.String() == "^(?:)$" { - _ = level.Warn(c.logger).Log("msg", "No filters specified for process collector. This will generate a very large number of metrics!") + _ = level.Warn(logger).Log("msg", "No filters specified for process collector. This will generate a very large number of metrics!") } commonLabels := make([]string, 0) @@ -286,18 +281,19 @@ type WorkerProcess struct { ProcessId uint64 } -func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) Collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) data := make([]perflibProcess, 0) - err := perflib.UnmarshalObject(ctx.PerfObjects["Process"], &data, c.logger) + err := perflib.UnmarshalObject(ctx.PerfObjects["Process"], &data, logger) if err != nil { return err } var workerProcesses []WorkerProcess if c.config.EnableWorkerProcess { - queryWorkerProcess := wmi.QueryAllForClass(&workerProcesses, "WorkerProcess", c.logger) + queryWorkerProcess := wmi.QueryAllForClass(&workerProcesses, "WorkerProcess", logger) if err := wmi.QueryNamespace(queryWorkerProcess, &workerProcesses, "root\\WebAdministration"); err != nil { - _ = level.Debug(c.logger).Log("msg", "Could not query WebAdministration namespace for IIS worker processes", "err", err) + _ = level.Debug(logger).Log("msg", "Could not query WebAdministration namespace for IIS worker processes", "err", err) } } diff --git a/pkg/collector/prometheus.go b/pkg/collector/prometheus.go index fc172bfc5..d3dea7d77 100644 --- a/pkg/collector/prometheus.go +++ b/pkg/collector/prometheus.go @@ -114,7 +114,7 @@ func (coll *Prometheus) Collect(ch chan<- prometheus.Metric) { for name, c := range coll.collectors.collectors { go func(name string, c Collector) { defer wg.Done() - outcome := coll.execute(name, c, scrapeContext, metricsBuffer) + outcome := coll.execute(coll.logger, name, c, scrapeContext, metricsBuffer) l.Lock() if !finished { collectorOutcomes[name] = outcome @@ -171,9 +171,9 @@ func (coll *Prometheus) Collect(ch chan<- prometheus.Metric) { l.Unlock() } -func (coll *Prometheus) execute(name string, c Collector, ctx *types.ScrapeContext, ch chan<- prometheus.Metric) collectorOutcome { +func (coll *Prometheus) execute(logger log.Logger, name string, c Collector, ctx *types.ScrapeContext, ch chan<- prometheus.Metric) collectorOutcome { t := time.Now() - err := c.Collect(ctx, ch) + err := c.Collect(ctx, logger, ch) duration := time.Since(t).Seconds() ch <- prometheus.MustNewConstMetric( coll.scrapeDurationDesc, diff --git a/pkg/collector/remote_fx/remote_fx.go b/pkg/collector/remote_fx/remote_fx.go index 4143b16c7..d02acee17 100644 --- a/pkg/collector/remote_fx/remote_fx.go +++ b/pkg/collector/remote_fx/remote_fx.go @@ -27,7 +27,6 @@ var ConfigDefaults = Config{} // https://wutils.com/wmi/root/cimv2/win32_perfrawdata_counters_remotefxgraphics/ type Collector struct { config Config - logger log.Logger // net baseTCPRTT *prometheus.Desc @@ -54,7 +53,7 @@ type Collector struct { sourceFramesPerSecond *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -63,8 +62,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -76,11 +73,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{"RemoteFX Network", "RemoteFX Graphics"}, nil } @@ -88,7 +81,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { // net c.baseTCPRTT = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "net_base_tcp_rtt_seconds"), @@ -217,13 +210,14 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collectRemoteFXNetworkCount(ctx, ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting terminal services session count metrics", "err", err) +func (c *Collector) Collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collectRemoteFXNetworkCount(ctx, logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting terminal services session count metrics", "err", err) return err } - if err := c.collectRemoteFXGraphicsCounters(ctx, ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting terminal services session count metrics", "err", err) + if err := c.collectRemoteFXGraphicsCounters(ctx, logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting terminal services session count metrics", "err", err) return err } return nil @@ -246,9 +240,10 @@ type perflibRemoteFxNetwork struct { RetransmissionRate float64 `perflib:"Percentage of packets that have been retransmitted"` } -func (c *Collector) collectRemoteFXNetworkCount(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collectRemoteFXNetworkCount(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) dst := make([]perflibRemoteFxNetwork, 0) - err := perflib.UnmarshalObject(ctx.PerfObjects["RemoteFX Network"], &dst, c.logger) + err := perflib.UnmarshalObject(ctx.PerfObjects["RemoteFX Network"], &dst, logger) if err != nil { return err } @@ -356,9 +351,10 @@ type perflibRemoteFxGraphics struct { SourceFramesPerSecond float64 `perflib:"Source Frames/Second"` } -func (c *Collector) collectRemoteFXGraphicsCounters(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collectRemoteFXGraphicsCounters(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) dst := make([]perflibRemoteFxGraphics, 0) - err := perflib.UnmarshalObject(ctx.PerfObjects["RemoteFX Graphics"], &dst, c.logger) + err := perflib.UnmarshalObject(ctx.PerfObjects["RemoteFX Graphics"], &dst, logger) if err != nil { return err } diff --git a/pkg/collector/scheduled_task/scheduled_task.go b/pkg/collector/scheduled_task/scheduled_task.go index c54f5bec9..019cdf445 100644 --- a/pkg/collector/scheduled_task/scheduled_task.go +++ b/pkg/collector/scheduled_task/scheduled_task.go @@ -32,7 +32,6 @@ var ConfigDefaults = Config{ type Collector struct { config Config - logger log.Logger lastResult *prometheus.Desc missedRuns *prometheus.Desc @@ -69,7 +68,7 @@ type ScheduledTask struct { type ScheduledTasks []ScheduledTask -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -86,8 +85,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -131,11 +128,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{}, nil } @@ -143,7 +136,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.lastResult = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "last_result"), "The result that was returned the last time the registered task was run", @@ -168,9 +161,10 @@ func (c *Collector) Build() error { return nil } -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) if err := c.collect(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting user metrics", "err", err) + _ = level.Error(logger).Log("msg", "failed collecting user metrics", "err", err) return err } diff --git a/pkg/collector/service/service.go b/pkg/collector/service/service.go index 6b9fc41ad..1bb141ca6 100644 --- a/pkg/collector/service/service.go +++ b/pkg/collector/service/service.go @@ -37,8 +37,6 @@ var ConfigDefaults = Config{ // A Collector is a Prometheus Collector for WMI Win32_Service metrics. type Collector struct { - logger log.Logger - serviceWhereClause *string useAPI *bool v2 *bool @@ -50,7 +48,7 @@ type Collector struct { StateV2 *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -59,7 +57,6 @@ func New(logger log.Logger, config *Config) *Collector { serviceWhereClause: &config.ServiceWhereClause, useAPI: &config.UseAPI, } - c.SetLogger(logger) return c } @@ -85,11 +82,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{}, nil } @@ -97,12 +90,14 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(logger log.Logger) error { + logger = log.With(logger, "collector", Name) + if utils.IsEmpty(c.serviceWhereClause) { - _ = level.Warn(c.logger).Log("msg", "No where-clause specified for service collector. This will generate a very large number of metrics!") + _ = level.Warn(logger).Log("msg", "No where-clause specified for service collector. This will generate a very large number of metrics!") } if *c.useAPI { - _ = level.Warn(c.logger).Log("msg", "API collection is enabled.") + _ = level.Warn(logger).Log("msg", "API collection is enabled.") } c.Information = prometheus.NewDesc( @@ -141,21 +136,22 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var err error switch { case *c.useAPI: - if err = c.collectAPI(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting API service metrics:", "err", err) + if err = c.collectAPI(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting API service metrics:", "err", err) } case *c.v2: - if err = c.collectAPIV2(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting API service metrics:", "err", err) + if err = c.collectAPIV2(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting API service metrics:", "err", err) } default: - if err = c.collectWMI(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting WMI service metrics:", "err", err) + if err = c.collectWMI(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting WMI service metrics:", "err", err) } } @@ -224,9 +220,9 @@ var ( } ) -func (c *Collector) collectWMI(ch chan<- prometheus.Metric) error { +func (c *Collector) collectWMI(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []Win32_Service - q := wmi.QueryAllWhere(&dst, *c.serviceWhereClause, c.logger) //nolint:staticcheck + q := wmi.QueryAllWhere(&dst, *c.serviceWhereClause, logger) //nolint:staticcheck if err := wmi.Query(q, &dst); err != nil { return err } @@ -292,7 +288,7 @@ func (c *Collector) collectWMI(ch chan<- prometheus.Metric) error { return nil } -func (c *Collector) collectAPI(ch chan<- prometheus.Metric) error { +func (c *Collector) collectAPI(logger log.Logger, ch chan<- prometheus.Metric) error { svcmgrConnection, err := mgr.Connect() if err != nil { return err @@ -311,14 +307,14 @@ func (c *Collector) collectAPI(ch chan<- prometheus.Metric) error { // Get UTF16 service name. serviceName, err := syscall.UTF16PtrFromString(service) if err != nil { - _ = level.Warn(c.logger).Log("msg", fmt.Sprintf("Service %s get name error: %#v", service, err)) + _ = level.Warn(logger).Log("msg", fmt.Sprintf("Service %s get name error: %#v", service, err)) return } // Open connection for service handler. serviceHandle, err := windows.OpenService(svcmgrConnection.Handle, serviceName, windows.GENERIC_READ) if err != nil { - _ = level.Warn(c.logger).Log("msg", fmt.Sprintf("Open service %s error: %#v", service, err)) + _ = level.Warn(logger).Log("msg", fmt.Sprintf("Open service %s error: %#v", service, err)) return } @@ -329,14 +325,14 @@ func (c *Collector) collectAPI(ch chan<- prometheus.Metric) error { // Get Service Configuration. serviceConfig, err := serviceManager.Config() if err != nil { - _ = level.Warn(c.logger).Log("msg", fmt.Sprintf("Get service %s config error: %#v", service, err)) + _ = level.Warn(logger).Log("msg", fmt.Sprintf("Get service %s config error: %#v", service, err)) return } // Get Service Current Status. serviceStatus, err := serviceManager.Query() if err != nil { - _ = level.Warn(c.logger).Log("msg", fmt.Sprintf("Get service %s status error: %#v", service, err)) + _ = level.Warn(logger).Log("msg", fmt.Sprintf("Get service %s status error: %#v", service, err)) return } @@ -384,15 +380,15 @@ func (c *Collector) collectAPI(ch chan<- prometheus.Metric) error { return nil } -func (c *Collector) collectAPIV2(ch chan<- prometheus.Metric) error { - services, err := c.queryAllServiceStates() +func (c *Collector) collectAPIV2(logger log.Logger, ch chan<- prometheus.Metric) error { + services, err := c.queryAllServiceStates(logger) if err != nil { - _ = level.Warn(c.logger).Log("msg", "Failed to query services", "err", err) + _ = level.Warn(logger).Log("msg", "Failed to query services", "err", err) return err } if services == nil { - _ = level.Warn(c.logger).Log("msg", "No services queried") + _ = level.Warn(logger).Log("msg", "No services queried") return nil } @@ -428,7 +424,7 @@ func (c *Collector) collectAPIV2(ch chan<- prometheus.Metric) error { // Copyright 2016-present Datadog, Inc. // // Source: https://github.com/DataDog/datadog-agent/blob/afbd8b6c87939c92610c654cb07fdfd439e4fb27/pkg/util/winutil/scmmonitor.go#L61-L96 -func (c *Collector) queryAllServiceStates() ([]windows.ENUM_SERVICE_STATUS_PROCESS, error) { +func (c *Collector) queryAllServiceStates(logger log.Logger) ([]windows.ENUM_SERVICE_STATUS_PROCESS, error) { // EnumServiceStatusEx requires only SC_MANAGER_ENUM_SERVICE. h, err := windows.OpenSCManager(nil, nil, windows.SC_MANAGER_ENUMERATE_SERVICE) if err != nil { @@ -438,7 +434,7 @@ func (c *Collector) queryAllServiceStates() ([]windows.ENUM_SERVICE_STATUS_PROCE m := &mgr.Mgr{Handle: h} defer func() { if err := m.Disconnect(); err != nil { - _ = level.Warn(c.logger).Log("msg", "Failed to disconnect from scm", "err", err) + _ = level.Warn(logger).Log("msg", "Failed to disconnect from scm", "err", err) } }() diff --git a/pkg/collector/smb/smb.go b/pkg/collector/smb/smb.go index 19d6c41c7..baee20490 100644 --- a/pkg/collector/smb/smb.go +++ b/pkg/collector/smb/smb.go @@ -21,13 +21,12 @@ var ConfigDefaults = Config{} type Collector struct { config Config - logger log.Logger treeConnectCount *prometheus.Desc currentOpenFileCount *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -36,8 +35,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -49,11 +46,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{ "SMB Server Shares", }, nil @@ -63,7 +56,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { // desc creates a new prometheus description desc := func(metricName string, description string, labels ...string) *prometheus.Desc { return prometheus.NewDesc( @@ -81,9 +74,10 @@ func (c *Collector) Build() error { } // Collect collects smb metrics and sends them to prometheus. -func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collectServerShares(ctx, ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed to collect server share metrics", "err", err) +func (c *Collector) Collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collectServerShares(ctx, logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed to collect server share metrics", "err", err) return err } @@ -99,9 +93,10 @@ type perflibServerShares struct { TreeConnectCount float64 `perflib:"Tree Connect Count"` } -func (c *Collector) collectServerShares(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collectServerShares(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var data []perflibServerShares - if err := perflib.UnmarshalObject(ctx.PerfObjects["SMB Server Shares"], &data, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["SMB Server Shares"], &data, logger); err != nil { return err } for _, instance := range data { diff --git a/pkg/collector/smbclient/smbclient.go b/pkg/collector/smbclient/smbclient.go index 72a10b36c..459d9e41a 100644 --- a/pkg/collector/smbclient/smbclient.go +++ b/pkg/collector/smbclient/smbclient.go @@ -23,7 +23,6 @@ var ConfigDefaults = Config{} type Collector struct { config Config - logger log.Logger readBytesTotal *prometheus.Desc readBytesTransmittedViaSMBDirectTotal *prometheus.Desc @@ -49,7 +48,7 @@ type Collector struct { requestSecs *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -58,8 +57,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -71,11 +68,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{ "SMB Client Shares", }, nil @@ -85,7 +78,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { // desc creates a new prometheus description desc := func(metricName string, description string, labels []string) *prometheus.Desc { return prometheus.NewDesc( @@ -185,9 +178,10 @@ func (c *Collector) Build() error { } // Collect collects smb client metrics and sends them to prometheus. -func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collectClientShares(ctx, ch); err != nil { - _ = level.Error(c.logger).Log("msg", "Error in ClientShares", "err", err) +func (c *Collector) Collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collectClientShares(ctx, logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "Error in ClientShares", "err", err) return err } @@ -221,9 +215,10 @@ type perflibClientShares struct { WriteRequestsPerSec float64 `perflib:"Write Requests/sec"` } -func (c *Collector) collectClientShares(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collectClientShares(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var data []perflibClientShares - if err := perflib.UnmarshalObject(ctx.PerfObjects["SMB Client Shares"], &data, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["SMB Client Shares"], &data, logger); err != nil { return err } for _, instance := range data { diff --git a/pkg/collector/smtp/smtp.go b/pkg/collector/smtp/smtp.go index b25156f5a..1db47a9fe 100644 --- a/pkg/collector/smtp/smtp.go +++ b/pkg/collector/smtp/smtp.go @@ -28,7 +28,6 @@ var ConfigDefaults = Config{ type Collector struct { config Config - logger log.Logger badMailedMessagesBadPickupFileTotal *prometheus.Desc badMailedMessagesGeneralFailureTotal *prometheus.Desc @@ -74,7 +73,7 @@ type Collector struct { routingTableLookupsTotal *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -91,8 +90,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -136,11 +133,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{"SMTP Server"}, nil } @@ -148,8 +141,10 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { - _ = level.Info(c.logger).Log("msg", "smtp collector is in an experimental state! Metrics for this collector have not been tested.") +func (c *Collector) Build(logger log.Logger) error { + logger = log.With(logger, "collector", Name) + + _ = level.Info(logger).Log("msg", "smtp collector is in an experimental state! Metrics for this collector have not been tested.") c.badMailedMessagesBadPickupFileTotal = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "badmailed_messages_bad_pickup_file_total"), @@ -409,9 +404,10 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collect(ctx, ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting smtp metrics", "err", err) +func (c *Collector) Collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collect(ctx, logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting smtp metrics", "err", err) return err } return nil @@ -465,9 +461,10 @@ type PerflibSMTPServer struct { RoutingTableLookupsTotal float64 `perflib:"Routing Table Lookups Total"` } -func (c *Collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var dst []PerflibSMTPServer - if err := perflib.UnmarshalObject(ctx.PerfObjects["SMTP Server"], &dst, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["SMTP Server"], &dst, logger); err != nil { return err } diff --git a/pkg/collector/system/system.go b/pkg/collector/system/system.go index 0e97eaed1..611794f36 100644 --- a/pkg/collector/system/system.go +++ b/pkg/collector/system/system.go @@ -20,7 +20,6 @@ var ConfigDefaults = Config{} // A Collector is a Prometheus Collector for WMI metrics. type Collector struct { config Config - logger log.Logger contextSwitchesTotal *prometheus.Desc exceptionDispatchesTotal *prometheus.Desc @@ -30,7 +29,7 @@ type Collector struct { threads *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -39,8 +38,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -52,11 +49,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{"System"}, nil } @@ -64,7 +57,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.contextSwitchesTotal = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "context_switches_total"), "Total number of context switches (WMI source: PerfOS_System.ContextSwitchesPersec)", @@ -106,9 +99,10 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collect(ctx, ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting system metrics", "err", err) +func (c *Collector) Collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collect(ctx, logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting system metrics", "err", err) return err } return nil @@ -125,9 +119,10 @@ type system struct { Threads float64 `perflib:"Threads"` } -func (c *Collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var dst []system - if err := perflib.UnmarshalObject(ctx.PerfObjects["System"], &dst, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["System"], &dst, logger); err != nil { return err } diff --git a/pkg/collector/tcp/tcp.go b/pkg/collector/tcp/tcp.go index f874b88a7..c7229bfa2 100644 --- a/pkg/collector/tcp/tcp.go +++ b/pkg/collector/tcp/tcp.go @@ -20,7 +20,6 @@ var ConfigDefaults = Config{} // A Collector is a Prometheus Collector for WMI Win32_PerfRawData_Tcpip_TCPv{4,6} metrics. type Collector struct { config Config - logger log.Logger connectionFailures *prometheus.Desc connectionsActive *prometheus.Desc @@ -33,7 +32,7 @@ type Collector struct { segmentsSentTotal *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -42,8 +41,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -55,11 +52,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{"TCPv4"}, nil } @@ -67,7 +60,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.connectionFailures = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "connection_failures_total"), "(TCP.ConnectionFailures)", @@ -127,9 +120,10 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collect(ctx, ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting tcp metrics", "err", err) +func (c *Collector) Collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collect(ctx, logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting tcp metrics", "err", err) return err } return nil @@ -207,11 +201,12 @@ func writeTCPCounters(metrics tcp, labels []string, c *Collector, ch chan<- prom ) } -func (c *Collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var dst []tcp // TCPv4 counters - if err := perflib.UnmarshalObject(ctx.PerfObjects["TCPv4"], &dst, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["TCPv4"], &dst, logger); err != nil { return err } if len(dst) != 0 { @@ -219,7 +214,7 @@ func (c *Collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metri } // TCPv6 counters - if err := perflib.UnmarshalObject(ctx.PerfObjects["TCPv6"], &dst, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["TCPv6"], &dst, logger); err != nil { return err } if len(dst) != 0 { diff --git a/pkg/collector/teradici_pcoip/teradici_pcoip.go b/pkg/collector/teradici_pcoip/teradici_pcoip.go index abf766156..11c3caa4e 100644 --- a/pkg/collector/teradici_pcoip/teradici_pcoip.go +++ b/pkg/collector/teradici_pcoip/teradici_pcoip.go @@ -27,7 +27,6 @@ var ConfigDefaults = Config{} // win32_PerfRawData_TeradiciPerf_PCoIPSessionUsbStatistics. type Collector struct { config Config - logger log.Logger audioBytesReceived *prometheus.Desc audioBytesSent *prometheus.Desc @@ -72,7 +71,7 @@ type Collector struct { usbTXBWKBitPerSec *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -81,8 +80,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -94,11 +91,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{}, nil } @@ -106,8 +99,9 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { - _ = level.Warn(c.logger).Log("msg", "teradici_pcoip collector is deprecated and will be removed in the future.") +func (c *Collector) Build(logger log.Logger) error { + _ = level.Warn(logger). + Log("msg", "teradici_pcoip collector is deprecated and will be removed in the future.", "collector", Name) c.audioBytesReceived = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "audio_bytes_received_total"), @@ -340,25 +334,26 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collectAudio(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting teradici session audio metrics", "err", err) +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collectAudio(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting teradici session audio metrics", "err", err) return err } - if err := c.collectGeneral(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting teradici session general metrics", "err", err) + if err := c.collectGeneral(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting teradici session general metrics", "err", err) return err } - if err := c.collectImaging(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting teradici session imaging metrics", "err", err) + if err := c.collectImaging(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting teradici session imaging metrics", "err", err) return err } - if err := c.collectNetwork(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting teradici session network metrics", "err", err) + if err := c.collectNetwork(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting teradici session network metrics", "err", err) return err } - if err := c.collectUsb(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting teradici session USB metrics", "err", err) + if err := c.collectUsb(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting teradici session USB metrics", "err", err) return err } return nil @@ -416,9 +411,9 @@ type win32_PerfRawData_TeradiciPerf_PCoIPSessionUsbStatistics struct { USBTXBWKBitPerSec uint64 } -func (c *Collector) collectAudio(ch chan<- prometheus.Metric) error { +func (c *Collector) collectAudio(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []win32_PerfRawData_TeradiciPerf_PCoIPSessionAudioStatistics - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } @@ -459,9 +454,9 @@ func (c *Collector) collectAudio(ch chan<- prometheus.Metric) error { return nil } -func (c *Collector) collectGeneral(ch chan<- prometheus.Metric) error { +func (c *Collector) collectGeneral(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []win32_PerfRawData_TeradiciPerf_PCoIPSessionGeneralStatistics - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } @@ -514,9 +509,9 @@ func (c *Collector) collectGeneral(ch chan<- prometheus.Metric) error { return nil } -func (c *Collector) collectImaging(ch chan<- prometheus.Metric) error { +func (c *Collector) collectImaging(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []win32_PerfRawData_TeradiciPerf_PCoIPSessionImagingStatistics - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } @@ -593,9 +588,9 @@ func (c *Collector) collectImaging(ch chan<- prometheus.Metric) error { return nil } -func (c *Collector) collectNetwork(ch chan<- prometheus.Metric) error { +func (c *Collector) collectNetwork(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []win32_PerfRawData_TeradiciPerf_PCoIPSessionNetworkStatistics - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } @@ -666,9 +661,9 @@ func (c *Collector) collectNetwork(ch chan<- prometheus.Metric) error { return nil } -func (c *Collector) collectUsb(ch chan<- prometheus.Metric) error { +func (c *Collector) collectUsb(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []win32_PerfRawData_TeradiciPerf_PCoIPSessionUsbStatistics - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } diff --git a/pkg/collector/terminal_services/terminal_services.go b/pkg/collector/terminal_services/terminal_services.go index 4cce9f469..d6658b3d2 100644 --- a/pkg/collector/terminal_services/terminal_services.go +++ b/pkg/collector/terminal_services/terminal_services.go @@ -53,7 +53,6 @@ func isConnectionBrokerServer(logger log.Logger) bool { // https://wutils.com/wmi/root/cimv2/win32_perfrawdata_localsessionmanager_terminalservices/ type Collector struct { config Config - logger log.Logger connectionBrokerEnabled bool @@ -76,7 +75,7 @@ type Collector struct { workingSetPeak *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -85,8 +84,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -98,11 +95,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{ "Terminal Services Session", "Remote Desktop Connection Broker Counterset", @@ -118,8 +111,10 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { - c.connectionBrokerEnabled = isConnectionBrokerServer(c.logger) +func (c *Collector) Build(logger log.Logger) error { + logger = log.With(logger, "collector", Name) + + c.connectionBrokerEnabled = isConnectionBrokerServer(logger) c.sessionInfo = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "session_info"), @@ -224,20 +219,21 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collectWTSSessions(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting terminal services session infos", "err", err) +func (c *Collector) Collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collectWTSSessions(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting terminal services session infos", "err", err) return err } - if err := c.collectTSSessionCounters(ctx, ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting terminal services session count metrics", "err", err) + if err := c.collectTSSessionCounters(ctx, logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting terminal services session count metrics", "err", err) return err } // only collect CollectionBrokerPerformance if host is a Connection Broker if c.connectionBrokerEnabled { - if err := c.collectCollectionBrokerPerformanceCounter(ctx, ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting Connection Broker performance metrics", "err", err) + if err := c.collectCollectionBrokerPerformanceCounter(ctx, logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting Connection Broker performance metrics", "err", err) return err } } @@ -263,9 +259,10 @@ type perflibTerminalServicesSession struct { WorkingSetPeak float64 `perflib:"Working Set Peak"` } -func (c *Collector) collectTSSessionCounters(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collectTSSessionCounters(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) dst := make([]perflibTerminalServicesSession, 0) - err := perflib.UnmarshalObject(ctx.PerfObjects["Terminal Services Session"], &dst, c.logger) + err := perflib.UnmarshalObject(ctx.PerfObjects["Terminal Services Session"], &dst, logger) if err != nil { return err } @@ -386,9 +383,10 @@ type perflibRemoteDesktopConnectionBrokerCounterset struct { FailedConnections float64 `perflib:"Failed Connections"` } -func (c *Collector) collectCollectionBrokerPerformanceCounter(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collectCollectionBrokerPerformanceCounter(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) dst := make([]perflibRemoteDesktopConnectionBrokerCounterset, 0) - err := perflib.UnmarshalObject(ctx.PerfObjects["Remote Desktop Connection Broker Counterset"], &dst, c.logger) + err := perflib.UnmarshalObject(ctx.PerfObjects["Remote Desktop Connection Broker Counterset"], &dst, logger) if err != nil { return err } @@ -420,8 +418,8 @@ func (c *Collector) collectCollectionBrokerPerformanceCounter(ctx *types.ScrapeC return nil } -func (c *Collector) collectWTSSessions(ch chan<- prometheus.Metric) error { - sessions, err := wtsapi32.WTSEnumerateSessionsEx(c.hServer, c.logger) +func (c *Collector) collectWTSSessions(logger log.Logger, ch chan<- prometheus.Metric) error { + sessions, err := wtsapi32.WTSEnumerateSessionsEx(c.hServer, logger) if err != nil { return fmt.Errorf("failed to enumerate WTS sessions: %w", err) } diff --git a/pkg/collector/textfile/textfile.go b/pkg/collector/textfile/textfile.go index e625084cc..1d64ac224 100644 --- a/pkg/collector/textfile/textfile.go +++ b/pkg/collector/textfile/textfile.go @@ -48,7 +48,6 @@ var ConfigDefaults = Config{ type Collector struct { config Config - logger log.Logger // Only set for testing to get predictable output. mTime *float64 @@ -56,7 +55,7 @@ type Collector struct { mTimeDesc *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -69,8 +68,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -99,11 +96,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{}, nil } @@ -111,9 +104,9 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { - _ = level.Info(c.logger). - Log("msg", "textfile Collector directories: "+strings.Join(c.config.TextFileDirectories, ",")) +func (c *Collector) Build(logger log.Logger) error { + _ = level.Info(logger). + Log("msg", "textfile Collector directories: "+strings.Join(c.config.TextFileDirectories, ","), "collector", Name) c.mTimeDesc = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, "textfile", "mtime_seconds"), @@ -150,7 +143,7 @@ func duplicateMetricEntry(metricFamilies []*dto.MetricFamily) bool { return false } -func (c *Collector) convertMetricFamily(metricFamily *dto.MetricFamily, ch chan<- prometheus.Metric) { +func (c *Collector) convertMetricFamily(logger log.Logger, metricFamily *dto.MetricFamily, ch chan<- prometheus.Metric) { var valType prometheus.ValueType var val float64 @@ -166,7 +159,7 @@ func (c *Collector) convertMetricFamily(metricFamily *dto.MetricFamily, ch chan< for _, metric := range metricFamily.GetMetric() { if metric.TimestampMs != nil { - _ = level.Warn(c.logger).Log("msg", fmt.Sprintf("Ignoring unsupported custom timestamp on textfile Collector metric %v", metric)) + _ = level.Warn(logger).Log("msg", fmt.Sprintf("Ignoring unsupported custom timestamp on textfile Collector metric %v", metric)) } labels := metric.GetLabel() @@ -236,7 +229,7 @@ func (c *Collector) convertMetricFamily(metricFamily *dto.MetricFamily, ch chan< buckets, values..., ) default: - _ = level.Error(c.logger).Log("msg", "unknown metric type for file") + _ = level.Error(logger).Log("msg", "unknown metric type for file") continue } if metricType == dto.MetricType_GAUGE || metricType == dto.MetricType_COUNTER || metricType == dto.MetricType_UNTYPED { @@ -297,7 +290,8 @@ func (cr carriageReturnFilteringReader) Read(p []byte) (int, error) { } // Collect implements the Collector interface. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) errorMetric := 0.0 mTimes := map[string]time.Time{} @@ -310,26 +304,26 @@ func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) for _, directory := range c.config.TextFileDirectories { err := filepath.WalkDir(directory, func(path string, dirEntry os.DirEntry, err error) error { if err != nil { - _ = level.Error(c.logger).Log("msg", "Error reading directory: "+path, "err", err) + _ = level.Error(logger).Log("msg", "Error reading directory: "+path, "err", err) errorMetric = 1.0 return nil } if !dirEntry.IsDir() && strings.HasSuffix(dirEntry.Name(), ".prom") { - _ = level.Debug(c.logger).Log("msg", "Processing file: "+path) - families_array, err := scrapeFile(path, c.logger) + _ = level.Debug(logger).Log("msg", "Processing file: "+path) + families_array, err := scrapeFile(path, logger) if err != nil { - _ = level.Error(c.logger).Log("msg", fmt.Sprintf("Error scraping file: %q. Skip File.", path), "err", err) + _ = level.Error(logger).Log("msg", fmt.Sprintf("Error scraping file: %q. Skip File.", path), "err", err) errorMetric = 1.0 return nil } fileInfo, err := os.Stat(path) if err != nil { - _ = level.Error(c.logger).Log("msg", fmt.Sprintf("Error reading file info: %q. Skip File.", path), "err", err) + _ = level.Error(logger).Log("msg", fmt.Sprintf("Error reading file info: %q. Skip File.", path), "err", err) errorMetric = 1.0 return nil } if _, hasName := mTimes[fileInfo.Name()]; hasName { - _ = level.Error(c.logger).Log("msg", fmt.Sprintf("Duplicate filename detected: %q. Skip File.", path)) + _ = level.Error(logger).Log("msg", fmt.Sprintf("Duplicate filename detected: %q. Skip File.", path)) errorMetric = 1.0 return nil } @@ -339,18 +333,18 @@ func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) return nil }) if err != nil && directory != "" { - _ = level.Error(c.logger).Log("msg", "Error reading textfile Collector directory: "+directory, "err", err) + _ = level.Error(logger).Log("msg", "Error reading textfile Collector directory: "+directory, "err", err) errorMetric = 1.0 } } // If duplicates are detected across *multiple* files, return error. if duplicateMetricEntry(metricFamilies) { - _ = level.Error(c.logger).Log("msg", "Duplicate metrics detected across multiple files") + _ = level.Error(logger).Log("msg", "Duplicate metrics detected across multiple files") errorMetric = 1.0 } else { for _, mf := range metricFamilies { - c.convertMetricFamily(mf, ch) + c.convertMetricFamily(logger, mf, ch) } } diff --git a/pkg/collector/textfile/textfile_test_test.go b/pkg/collector/textfile/textfile_test_test.go index 78c975fcf..246aa56d3 100644 --- a/pkg/collector/textfile/textfile_test_test.go +++ b/pkg/collector/textfile/textfile_test_test.go @@ -19,15 +19,16 @@ var baseDir = "../../../tools/textfile-test" func TestMultipleDirectories(t *testing.T) { t.Parallel() + logger := log.NewLogfmtLogger(os.Stdout) testDir := baseDir + "/multiple-dirs" testDirs := fmt.Sprintf("%[1]s/dir1,%[1]s/dir2,%[1]s/dir3", testDir) - textFileCollector := textfile.New(log.NewLogfmtLogger(os.Stdout), &textfile.Config{ + textFileCollector := textfile.New(&textfile.Config{ TextFileDirectories: strings.Split(testDirs, ","), }) collectors := collector.New(map[string]collector.Collector{textfile.Name: textFileCollector}) - require.NoError(t, collectors.Build()) + require.NoError(t, collectors.Build(logger)) scrapeContext, err := collectors.PrepareScrapeContext() if err != nil { @@ -47,7 +48,7 @@ func TestMultipleDirectories(t *testing.T) { } }() - err = textFileCollector.Collect(scrapeContext, metrics) + err = textFileCollector.Collect(scrapeContext, logger, metrics) if err != nil { t.Errorf("Unexpected error %s", err) } @@ -62,13 +63,14 @@ func TestMultipleDirectories(t *testing.T) { func TestDuplicateFileName(t *testing.T) { t.Parallel() + logger := log.NewLogfmtLogger(os.Stdout) testDir := baseDir + "/duplicate-filename" - textFileCollector := textfile.New(log.NewLogfmtLogger(os.Stdout), &textfile.Config{ + textFileCollector := textfile.New(&textfile.Config{ TextFileDirectories: []string{testDir}, }) collectors := collector.New(map[string]collector.Collector{textfile.Name: textFileCollector}) - require.NoError(t, collectors.Build()) + require.NoError(t, collectors.Build(logger)) scrapeContext, err := collectors.PrepareScrapeContext() if err != nil { @@ -87,7 +89,7 @@ func TestDuplicateFileName(t *testing.T) { got += metric.String() } }() - err = textFileCollector.Collect(scrapeContext, metrics) + err = textFileCollector.Collect(scrapeContext, logger, metrics) if err != nil { t.Errorf("Unexpected error %s", err) } diff --git a/pkg/collector/thermalzone/thermalzone.go b/pkg/collector/thermalzone/thermalzone.go index a72ea5dbe..3ac746ed9 100644 --- a/pkg/collector/thermalzone/thermalzone.go +++ b/pkg/collector/thermalzone/thermalzone.go @@ -22,14 +22,13 @@ var ConfigDefaults = Config{} // A Collector is a Prometheus Collector for WMI Win32_PerfRawData_Counters_ThermalZoneInformation metrics. type Collector struct { config Config - logger log.Logger percentPassiveLimit *prometheus.Desc temperature *prometheus.Desc throttleReasons *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -38,8 +37,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -51,11 +48,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{}, nil } @@ -63,7 +56,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.temperature = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "temperature_celsius"), "(Temperature)", @@ -93,9 +86,10 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collect(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting thermalzone metrics", "err", err) +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collect(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting thermalzone metrics", "err", err) return err } return nil @@ -111,9 +105,9 @@ type Win32_PerfRawData_Counters_ThermalZoneInformation struct { ThrottleReasons uint32 } -func (c *Collector) collect(ch chan<- prometheus.Metric) error { +func (c *Collector) collect(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []Win32_PerfRawData_Counters_ThermalZoneInformation - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } diff --git a/pkg/collector/time/time.go b/pkg/collector/time/time.go index e78d98d94..dbc090331 100644 --- a/pkg/collector/time/time.go +++ b/pkg/collector/time/time.go @@ -23,7 +23,6 @@ var ConfigDefaults = Config{} // Collector is a Prometheus Collector for Perflib counter metrics. type Collector struct { config Config - logger log.Logger clockFrequencyAdjustmentPPBTotal *prometheus.Desc computedTimeOffset *prometheus.Desc @@ -33,7 +32,7 @@ type Collector struct { ntpServerOutgoingResponsesTotal *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -42,8 +41,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -55,11 +52,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{"Windows Time Service"}, nil } @@ -67,7 +60,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { if winversion.WindowsVersionFloat <= 6.1 { return errors.New("Windows version older than Server 2016 detected. The time collector will not run and should be disabled via CLI flags or configuration file") } @@ -113,9 +106,10 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collect(ctx, ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting time metrics", "err", err) +func (c *Collector) Collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collect(ctx, logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting time metrics", "err", err) return err } return nil @@ -131,9 +125,10 @@ type windowsTime struct { NTPServerOutgoingResponsesTotal float64 `perflib:"NTP Server Outgoing Responses"` } -func (c *Collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { +func (c *Collector) collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) var dst []windowsTime // Single-instance class, array is required but will have single entry. - if err := perflib.UnmarshalObject(ctx.PerfObjects["Windows Time Service"], &dst, c.logger); err != nil { + if err := perflib.UnmarshalObject(ctx.PerfObjects["Windows Time Service"], &dst, logger); err != nil { return err } diff --git a/pkg/collector/types.go b/pkg/collector/types.go index cc37e302f..eee2e6cf9 100644 --- a/pkg/collector/types.go +++ b/pkg/collector/types.go @@ -8,29 +8,24 @@ import ( ) type Collectors struct { - logger log.Logger - collectors Map perfCounterQuery string } -type Map map[string]Collector - type ( - Builder func(logger log.Logger) Collector BuilderWithFlags[C Collector] func(*kingpin.Application) C + Map map[string]Collector ) // Collector interface that a collector has to implement. type Collector interface { - Build() error + Build(logger log.Logger) error // Close closes the collector Close() error // GetName get the name of the collector GetName() string // GetPerfCounter returns the perf counter required by the collector - GetPerfCounter() ([]string, error) + GetPerfCounter(logger log.Logger) ([]string, error) // Collect Get new metrics and expose them via prometheus registry. - Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) (err error) - SetLogger(logger log.Logger) + Collect(ctx *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) (err error) } diff --git a/pkg/collector/vmware/vmware.go b/pkg/collector/vmware/vmware.go index 52514d114..8d5e63577 100644 --- a/pkg/collector/vmware/vmware.go +++ b/pkg/collector/vmware/vmware.go @@ -23,7 +23,6 @@ var ConfigDefaults = Config{} // A Collector is a Prometheus Collector for WMI Win32_PerfRawData_vmGuestLib_VMem/Win32_PerfRawData_vmGuestLib_VCPU metrics. type Collector struct { config Config - logger log.Logger memActive *prometheus.Desc memBallooned *prometheus.Desc @@ -47,7 +46,7 @@ type Collector struct { hostProcessorSpeedMHz *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -56,8 +55,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -69,11 +66,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{}, nil } @@ -81,7 +74,7 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { +func (c *Collector) Build(_ log.Logger) error { c.memActive = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "mem_active_bytes"), "(MemActiveMB)", @@ -202,13 +195,14 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collectMem(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting vmware memory metrics", "err", err) +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collectMem(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting vmware memory metrics", "err", err) return err } - if err := c.collectCpu(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting vmware cpu metrics", "err", err) + if err := c.collectCpu(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting vmware cpu metrics", "err", err) return err } return nil @@ -239,9 +233,9 @@ type Win32_PerfRawData_vmGuestLib_VCPU struct { HostProcessorSpeedMHz uint64 } -func (c *Collector) collectMem(ch chan<- prometheus.Metric) error { +func (c *Collector) collectMem(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []Win32_PerfRawData_vmGuestLib_VMem - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } @@ -328,9 +322,9 @@ func mbToBytes(mb uint64) float64 { return float64(mb * 1024 * 1024) } -func (c *Collector) collectCpu(ch chan<- prometheus.Metric) error { +func (c *Collector) collectCpu(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []Win32_PerfRawData_vmGuestLib_VCPU - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } diff --git a/pkg/collector/vmware_blast/vmware_blast.go b/pkg/collector/vmware_blast/vmware_blast.go index 4162f68ab..f32118596 100644 --- a/pkg/collector/vmware_blast/vmware_blast.go +++ b/pkg/collector/vmware_blast/vmware_blast.go @@ -33,7 +33,6 @@ var ConfigDefaults = Config{} type Collector struct { config Config - logger log.Logger audioReceivedBytes *prometheus.Desc audioReceivedPackets *prometheus.Desc @@ -117,7 +116,7 @@ type Collector struct { windowsMediaMMRTransmittedPackets *prometheus.Desc } -func New(logger log.Logger, config *Config) *Collector { +func New(config *Config) *Collector { if config == nil { config = &ConfigDefaults } @@ -126,8 +125,6 @@ func New(logger log.Logger, config *Config) *Collector { config: *config, } - c.SetLogger(logger) - return c } @@ -139,11 +136,7 @@ func (c *Collector) GetName() string { return Name } -func (c *Collector) SetLogger(logger log.Logger) { - c.logger = log.With(logger, "collector", Name) -} - -func (c *Collector) GetPerfCounter() ([]string, error) { +func (c *Collector) GetPerfCounter(_ log.Logger) ([]string, error) { return []string{}, nil } @@ -151,8 +144,9 @@ func (c *Collector) Close() error { return nil } -func (c *Collector) Build() error { - _ = level.Warn(c.logger).Log("msg", "vmware_blast collector is deprecated and will be removed in the future.") +func (c *Collector) Build(logger log.Logger) error { + _ = level.Warn(logger). + Log("msg", "vmware_blast collector is deprecated and will be removed in the future.", "collector", Name) c.audioReceivedBytes = prometheus.NewDesc( prometheus.BuildFQName(types.Namespace, Name, "audio_received_bytes_total"), @@ -584,53 +578,54 @@ func (c *Collector) Build() error { // Collect sends the metric values for each metric // to the provided prometheus Metric channel. -func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { - if err := c.collectAudio(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting vmware blast audio metrics", "err", err) +func (c *Collector) Collect(_ *types.ScrapeContext, logger log.Logger, ch chan<- prometheus.Metric) error { + logger = log.With(logger, "collector", Name) + if err := c.collectAudio(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting vmware blast audio metrics", "err", err) return err } - if err := c.collectCdr(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting vmware blast CDR metrics", "err", err) + if err := c.collectCdr(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting vmware blast CDR metrics", "err", err) return err } - if err := c.collectClipboard(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting vmware blast clipboard metrics", "err", err) + if err := c.collectClipboard(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting vmware blast clipboard metrics", "err", err) return err } - if err := c.collectHtml5Mmr(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting vmware blast HTML5 MMR metrics", "err", err) + if err := c.collectHtml5Mmr(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting vmware blast HTML5 MMR metrics", "err", err) return err } - if err := c.collectImaging(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting vmware blast imaging metrics", "err", err) + if err := c.collectImaging(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting vmware blast imaging metrics", "err", err) return err } - if err := c.collectRtav(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting vmware blast RTAV metrics", "err", err) + if err := c.collectRtav(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting vmware blast RTAV metrics", "err", err) return err } - if err := c.collectSerialPortandScanner(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting vmware blast serial port and scanner metrics", "err", err) + if err := c.collectSerialPortandScanner(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting vmware blast serial port and scanner metrics", "err", err) return err } - if err := c.collectSession(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting vmware blast metrics", "err", err) + if err := c.collectSession(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting vmware blast metrics", "err", err) return err } - if err := c.collectSkypeforBusinessControl(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting vmware blast skype for business control metrics", "err", err) + if err := c.collectSkypeforBusinessControl(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting vmware blast skype for business control metrics", "err", err) return err } - if err := c.collectThinPrint(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting vmware blast thin print metrics", "err", err) + if err := c.collectThinPrint(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting vmware blast thin print metrics", "err", err) return err } - if err := c.collectUsb(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting vmware blast USB metrics", "err", err) + if err := c.collectUsb(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting vmware blast USB metrics", "err", err) return err } - if err := c.collectWindowsMediaMmr(ch); err != nil { - _ = level.Error(c.logger).Log("msg", "failed collecting vmware blast windows media MMR metrics", "err", err) + if err := c.collectWindowsMediaMmr(logger, ch); err != nil { + _ = level.Error(logger).Log("msg", "failed collecting vmware blast windows media MMR metrics", "err", err) return err } return nil @@ -741,9 +736,9 @@ type win32_PerfRawData_Counters_VMwareBlastWindowsMediaMMRCounters struct { TransmittedPackets uint32 } -func (c *Collector) collectAudio(ch chan<- prometheus.Metric) error { +func (c *Collector) collectAudio(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []win32_PerfRawData_Counters_VMwareBlastAudioCounters - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } @@ -780,9 +775,9 @@ func (c *Collector) collectAudio(ch chan<- prometheus.Metric) error { return nil } -func (c *Collector) collectCdr(ch chan<- prometheus.Metric) error { +func (c *Collector) collectCdr(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []win32_PerfRawData_Counters_VMwareBlastCDRCounters - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } @@ -819,9 +814,9 @@ func (c *Collector) collectCdr(ch chan<- prometheus.Metric) error { return nil } -func (c *Collector) collectClipboard(ch chan<- prometheus.Metric) error { +func (c *Collector) collectClipboard(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []win32_PerfRawData_Counters_VMwareBlastClipboardCounters - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } @@ -858,9 +853,9 @@ func (c *Collector) collectClipboard(ch chan<- prometheus.Metric) error { return nil } -func (c *Collector) collectHtml5Mmr(ch chan<- prometheus.Metric) error { +func (c *Collector) collectHtml5Mmr(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []win32_PerfRawData_Counters_VMwareBlastHTML5MMRcounters - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } @@ -897,9 +892,9 @@ func (c *Collector) collectHtml5Mmr(ch chan<- prometheus.Metric) error { return nil } -func (c *Collector) collectImaging(ch chan<- prometheus.Metric) error { +func (c *Collector) collectImaging(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []win32_PerfRawData_Counters_VMwareBlastImagingCounters - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } @@ -984,9 +979,9 @@ func (c *Collector) collectImaging(ch chan<- prometheus.Metric) error { return nil } -func (c *Collector) collectRtav(ch chan<- prometheus.Metric) error { +func (c *Collector) collectRtav(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []win32_PerfRawData_Counters_VMwareBlastRTAVCounters - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } @@ -1023,9 +1018,9 @@ func (c *Collector) collectRtav(ch chan<- prometheus.Metric) error { return nil } -func (c *Collector) collectSerialPortandScanner(ch chan<- prometheus.Metric) error { +func (c *Collector) collectSerialPortandScanner(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []win32_PerfRawData_Counters_VMwareBlastSerialPortandScannerCounters - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } @@ -1062,9 +1057,9 @@ func (c *Collector) collectSerialPortandScanner(ch chan<- prometheus.Metric) err return nil } -func (c *Collector) collectSession(ch chan<- prometheus.Metric) error { +func (c *Collector) collectSession(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []win32_PerfRawData_Counters_VMwareBlastSessionCounters - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } @@ -1179,9 +1174,9 @@ func (c *Collector) collectSession(ch chan<- prometheus.Metric) error { return nil } -func (c *Collector) collectSkypeforBusinessControl(ch chan<- prometheus.Metric) error { +func (c *Collector) collectSkypeforBusinessControl(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []win32_PerfRawData_Counters_VMwareBlastSkypeforBusinessControlCounters - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } @@ -1218,9 +1213,9 @@ func (c *Collector) collectSkypeforBusinessControl(ch chan<- prometheus.Metric) return nil } -func (c *Collector) collectThinPrint(ch chan<- prometheus.Metric) error { +func (c *Collector) collectThinPrint(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []win32_PerfRawData_Counters_VMwareBlastThinPrintCounters - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } @@ -1257,9 +1252,9 @@ func (c *Collector) collectThinPrint(ch chan<- prometheus.Metric) error { return nil } -func (c *Collector) collectUsb(ch chan<- prometheus.Metric) error { +func (c *Collector) collectUsb(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []win32_PerfRawData_Counters_VMwareBlastUSBCounters - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } @@ -1296,9 +1291,9 @@ func (c *Collector) collectUsb(ch chan<- prometheus.Metric) error { return nil } -func (c *Collector) collectWindowsMediaMmr(ch chan<- prometheus.Metric) error { +func (c *Collector) collectWindowsMediaMmr(logger log.Logger, ch chan<- prometheus.Metric) error { var dst []win32_PerfRawData_Counters_VMwareBlastWindowsMediaMMRCounters - q := wmi.QueryAll(&dst, c.logger) + q := wmi.QueryAll(&dst, logger) if err := wmi.Query(q, &dst); err != nil { return err } diff --git a/pkg/testutils/testutils.go b/pkg/testutils/testutils.go index ce3034233..5120b02a6 100644 --- a/pkg/testutils/testutils.go +++ b/pkg/testutils/testutils.go @@ -15,10 +15,11 @@ import ( func FuncBenchmarkCollector[C collector.Collector](b *testing.B, name string, collectFunc collector.BuilderWithFlags[C]) { b.Helper() + logger := log.NewNopLogger() + c := collectFunc(kingpin.CommandLine) collectors := collector.New(map[string]collector.Collector{name: c}) - require.NoError(b, collectors.Build()) - collectors.SetLogger(log.NewNopLogger()) + require.NoError(b, collectors.Build(logger)) // Create perflib scrape context. // Some perflib collectors required a correct context, @@ -34,6 +35,6 @@ func FuncBenchmarkCollector[C collector.Collector](b *testing.B, name string, co }() for i := 0; i < b.N; i++ { - require.NoError(b, c.Collect(scrapeContext, metrics)) + require.NoError(b, c.Collect(scrapeContext, logger, metrics)) } }