diff --git a/.golangci.yml b/.golangci.yml index 1e676f3..9e3887e 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,4 +1,8 @@ --- +linters: + enable: + - sloglint + run: deadline: 5m skip-files: @@ -16,5 +20,3 @@ linters-settings: exclude-functions: # Used in HTTP handlers, any error is handled by the server itself. - (net/http.ResponseWriter).Write - # Never check for logger errors. - - (github.com/go-kit/log.Logger).Log diff --git a/collectors/monitoring_collector.go b/collectors/monitoring_collector.go index b6228a9..a2c1543 100644 --- a/collectors/monitoring_collector.go +++ b/collectors/monitoring_collector.go @@ -16,13 +16,12 @@ package collectors import ( "errors" "fmt" + "log/slog" "math" "strings" "sync" "time" - "github.com/go-kit/log" - "github.com/go-kit/log/level" "github.com/prometheus/client_golang/prometheus" "golang.org/x/net/context" "google.golang.org/api/monitoring/v3" @@ -53,7 +52,7 @@ type MonitoringCollector struct { lastScrapeDurationSecondsMetric prometheus.Gauge collectorFillMissingLabels bool monitoringDropDelegatedProjects bool - logger log.Logger + logger *slog.Logger counterStore DeltaCounterStore histogramStore DeltaHistogramStore aggregateDeltas bool @@ -120,10 +119,10 @@ type DeltaHistogramStore interface { ListMetrics(metricDescriptorName string) []*HistogramMetric } -func NewMonitoringCollector(projectID string, monitoringService *monitoring.Service, opts MonitoringCollectorOptions, logger log.Logger, counterStore DeltaCounterStore, histogramStore DeltaHistogramStore) (*MonitoringCollector, error) { +func NewMonitoringCollector(projectID string, monitoringService *monitoring.Service, opts MonitoringCollectorOptions, logger *slog.Logger, counterStore DeltaCounterStore, histogramStore DeltaHistogramStore) (*MonitoringCollector, error) { const subsystem = "monitoring" - logger = log.With(logger, "project_id", projectID) + logger = logger.With("project_id", projectID) apiCallsTotalMetric := prometheus.NewCounter( prometheus.CounterOpts{ @@ -237,7 +236,7 @@ func (c *MonitoringCollector) Collect(ch chan<- prometheus.Metric) { if err := c.reportMonitoringMetrics(ch, begun); err != nil { errorMetric = float64(1) c.scrapeErrorsTotalMetric.Inc() - level.Error(c.logger).Log("msg", "Error while getting Google Stackdriver Monitoring metrics", "err", err) + c.logger.Error("Error while getting Google Stackdriver Monitoring metrics", "err", err) } c.scrapeErrorsTotalMetric.Collect(ch) @@ -283,7 +282,7 @@ func (c *MonitoringCollector) reportMonitoringMetrics(ch chan<- prometheus.Metri wg.Add(1) go func(metricDescriptor *monitoring.MetricDescriptor, ch chan<- prometheus.Metric, startTime, endTime time.Time) { defer wg.Done() - level.Debug(c.logger).Log("msg", "retrieving Google Stackdriver Monitoring metrics for descriptor", "descriptor", metricDescriptor.Type) + c.logger.Debug("retrieving Google Stackdriver Monitoring metrics for descriptor", "descriptor", metricDescriptor.Type) filter := fmt.Sprintf("metric.type=\"%s\"", metricDescriptor.Type) if c.monitoringDropDelegatedProjects { filter = fmt.Sprintf( @@ -298,11 +297,11 @@ func (c *MonitoringCollector) reportMonitoringMetrics(ch chan<- prometheus.Metri ingestDelay := metricDescriptor.Metadata.IngestDelay ingestDelayDuration, err := time.ParseDuration(ingestDelay) if err != nil { - level.Error(c.logger).Log("msg", "error parsing ingest delay from metric metadata", "descriptor", metricDescriptor.Type, "err", err, "delay", ingestDelay) + c.logger.Error("error parsing ingest delay from metric metadata", "descriptor", metricDescriptor.Type, "err", err, "delay", ingestDelay) errChannel <- err return } - level.Debug(c.logger).Log("msg", "adding ingest delay", "descriptor", metricDescriptor.Type, "delay", ingestDelay) + c.logger.Debug("adding ingest delay", "descriptor", metricDescriptor.Type, "delay", ingestDelay) endTime = endTime.Add(ingestDelayDuration * -1) startTime = startTime.Add(ingestDelayDuration * -1) } @@ -313,7 +312,7 @@ func (c *MonitoringCollector) reportMonitoringMetrics(ch chan<- prometheus.Metri } } - level.Debug(c.logger).Log("msg", "retrieving Google Stackdriver Monitoring metrics with filter", "filter", filter) + c.logger.Debug("retrieving Google Stackdriver Monitoring metrics with filter", "filter", filter) timeSeriesListCall := c.monitoringService.Projects.TimeSeries.List(utils.ProjectResource(c.projectID)). Filter(filter). @@ -324,7 +323,7 @@ func (c *MonitoringCollector) reportMonitoringMetrics(ch chan<- prometheus.Metri c.apiCallsTotalMetric.Inc() page, err := timeSeriesListCall.Do() if err != nil { - level.Error(c.logger).Log("msg", "error retrieving Time Series metrics for descriptor", "descriptor", metricDescriptor.Type, "err", err) + c.logger.Error("error retrieving Time Series metrics for descriptor", "descriptor", metricDescriptor.Type, "err", err) errChannel <- err break } @@ -332,7 +331,7 @@ func (c *MonitoringCollector) reportMonitoringMetrics(ch chan<- prometheus.Metri break } if err := c.reportTimeSeriesMetrics(page, metricDescriptor, ch, begun); err != nil { - level.Error(c.logger).Log("msg", "error reporting Time Series metrics for descriptor", "descriptor", metricDescriptor.Type, "err", err) + c.logger.Error("error reporting Time Series metrics for descriptor", "descriptor", metricDescriptor.Type, "err", err) errChannel <- err break } @@ -368,7 +367,7 @@ func (c *MonitoringCollector) reportMonitoringMetrics(ch chan<- prometheus.Metri } if cached := c.descriptorCache.Lookup(metricsTypePrefix); cached != nil { - level.Debug(c.logger).Log("msg", "using cached Google Stackdriver Monitoring metric descriptors starting with", "prefix", metricsTypePrefix) + c.logger.Debug("using cached Google Stackdriver Monitoring metric descriptors starting with", "prefix", metricsTypePrefix) if err := metricDescriptorsFunction(cached); err != nil { errChannel <- err } @@ -381,7 +380,7 @@ func (c *MonitoringCollector) reportMonitoringMetrics(ch chan<- prometheus.Metri return metricDescriptorsFunction(r.MetricDescriptors) } - level.Debug(c.logger).Log("msg", "listing Google Stackdriver Monitoring metric descriptors starting with", "prefix", metricsTypePrefix) + c.logger.Debug("listing Google Stackdriver Monitoring metric descriptors starting with", "prefix", metricsTypePrefix) if err := c.monitoringService.Projects.MetricDescriptors.List(utils.ProjectResource(c.projectID)). Filter(filter). Pages(ctx, callback); err != nil { @@ -396,7 +395,7 @@ func (c *MonitoringCollector) reportMonitoringMetrics(ch chan<- prometheus.Metri wg.Wait() close(errChannel) - level.Debug(c.logger).Log("msg", "Done reporting monitoring metrics") + c.logger.Debug("Done reporting monitoring metrics") return <-errChannel } @@ -500,12 +499,12 @@ func (c *MonitoringCollector) reportTimeSeriesMetrics( if err == nil { timeSeriesMetrics.CollectNewConstHistogram(timeSeries, newestEndTime, labelKeys, dist, buckets, labelValues, timeSeries.MetricKind) } else { - level.Debug(c.logger).Log("msg", "discarding", "resource", timeSeries.Resource.Type, "metric", + c.logger.Debug("discarding", "resource", timeSeries.Resource.Type, "metric", timeSeries.Metric.Type, "err", err) } continue default: - level.Debug(c.logger).Log("msg", "discarding", "value_type", timeSeries.ValueType, "metric", timeSeries) + c.logger.Debug("discarding", "value_type", timeSeries.ValueType, "metric", timeSeries) continue } @@ -569,7 +568,7 @@ func (c *MonitoringCollector) generateHistogramBuckets( func (c *MonitoringCollector) keyExists(labelKeys []string, key string) bool { for _, item := range labelKeys { if item == key { - level.Debug(c.logger).Log("msg", "Found duplicate label key", "key", key) + c.logger.Debug("Found duplicate label key", "key", key) return true } } diff --git a/delta/counter.go b/delta/counter.go index 068b7f5..67da32c 100644 --- a/delta/counter.go +++ b/delta/counter.go @@ -15,13 +15,12 @@ package delta import ( "fmt" + "log/slog" "sort" "strings" "sync" "time" - "github.com/go-kit/log" - "github.com/go-kit/log/level" "google.golang.org/api/monitoring/v3" "github.com/prometheus-community/stackdriver_exporter/collectors" @@ -36,11 +35,11 @@ type MetricEntry struct { type InMemoryCounterStore struct { store *sync.Map ttl time.Duration - logger log.Logger + logger *slog.Logger } // NewInMemoryCounterStore returns an implementation of CounterStore which is persisted in-memory -func NewInMemoryCounterStore(logger log.Logger, ttl time.Duration) *InMemoryCounterStore { +func NewInMemoryCounterStore(logger *slog.Logger, ttl time.Duration) *InMemoryCounterStore { store := &InMemoryCounterStore{ store: &sync.Map{}, logger: logger, @@ -68,19 +67,19 @@ func (s *InMemoryCounterStore) Increment(metricDescriptor *monitoring.MetricDesc existing := entry.Collected[key] if existing == nil { - level.Debug(s.logger).Log("msg", "Tracking new counter", "fqName", currentValue.FqName, "key", key, "current_value", currentValue.Value, "incoming_time", currentValue.ReportTime) + s.logger.Debug("Tracking new counter", "fqName", currentValue.FqName, "key", key, "current_value", currentValue.Value, "incoming_time", currentValue.ReportTime) entry.Collected[key] = currentValue return } if existing.ReportTime.Before(currentValue.ReportTime) { - level.Debug(s.logger).Log("msg", "Incrementing existing counter", "fqName", currentValue.FqName, "key", key, "current_value", existing.Value, "adding", currentValue.Value, "last_reported_time", existing.ReportTime, "incoming_time", currentValue.ReportTime) + s.logger.Debug("Incrementing existing counter", "fqName", currentValue.FqName, "key", key, "current_value", existing.Value, "adding", currentValue.Value, "last_reported_time", existing.ReportTime, "incoming_time", currentValue.ReportTime) currentValue.Value = currentValue.Value + existing.Value entry.Collected[key] = currentValue return } - level.Debug(s.logger).Log("msg", "Ignoring old sample for counter", "fqName", currentValue.FqName, "key", key, "last_reported_time", existing.ReportTime, "incoming_time", currentValue.ReportTime) + s.logger.Debug("Ignoring old sample for counter", "fqName", currentValue.FqName, "key", key, "last_reported_time", existing.ReportTime, "incoming_time", currentValue.ReportTime) } func toCounterKey(c *collectors.ConstMetric) uint64 { @@ -118,7 +117,7 @@ func (s *InMemoryCounterStore) ListMetrics(metricDescriptorName string) []*colle for key, collected := range entry.Collected { //Scan and remove metrics which are outside the TTL if ttlWindowStart.After(collected.CollectionTime) { - level.Debug(s.logger).Log("msg", "Deleting counter entry outside of TTL", "key", key, "fqName", collected.FqName) + s.logger.Debug("Deleting counter entry outside of TTL", "key", key, "fqName", collected.FqName) delete(entry.Collected, key) continue } diff --git a/delta/counter_test.go b/delta/counter_test.go index 31fcece..2236c81 100644 --- a/delta/counter_test.go +++ b/delta/counter_test.go @@ -18,7 +18,7 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "github.com/prometheus/common/promlog" + "github.com/prometheus/common/promslog" "google.golang.org/api/monitoring/v3" "github.com/prometheus-community/stackdriver_exporter/collectors" @@ -31,7 +31,7 @@ var _ = Describe("Counter", func() { descriptor := &monitoring.MetricDescriptor{Name: "This is a metric"} BeforeEach(func() { - store = delta.NewInMemoryCounterStore(promlog.New(&promlog.Config{}), time.Minute) + store = delta.NewInMemoryCounterStore(promslog.New(&promslog.Config{}), time.Minute) metric = &collectors.ConstMetric{ FqName: "counter_name", LabelKeys: []string{"labelKey"}, diff --git a/delta/histogram.go b/delta/histogram.go index 2d8d919..e82162a 100644 --- a/delta/histogram.go +++ b/delta/histogram.go @@ -15,13 +15,12 @@ package delta import ( "fmt" + "log/slog" "sort" "strings" "sync" "time" - "github.com/go-kit/log" - "github.com/go-kit/log/level" "google.golang.org/api/monitoring/v3" "github.com/prometheus-community/stackdriver_exporter/collectors" @@ -36,11 +35,11 @@ type HistogramEntry struct { type InMemoryHistogramStore struct { store *sync.Map ttl time.Duration - logger log.Logger + logger *slog.Logger } // NewInMemoryHistogramStore returns an implementation of HistogramStore which is persisted in-memory -func NewInMemoryHistogramStore(logger log.Logger, ttl time.Duration) *InMemoryHistogramStore { +func NewInMemoryHistogramStore(logger *slog.Logger, ttl time.Duration) *InMemoryHistogramStore { store := &InMemoryHistogramStore{ store: &sync.Map{}, logger: logger, @@ -68,20 +67,20 @@ func (s *InMemoryHistogramStore) Increment(metricDescriptor *monitoring.MetricDe existing := entry.Collected[key] if existing == nil { - level.Debug(s.logger).Log("msg", "Tracking new histogram", "fqName", currentValue.FqName, "key", key, "incoming_time", currentValue.ReportTime) + s.logger.Debug("Tracking new histogram", "fqName", currentValue.FqName, "key", key, "incoming_time", currentValue.ReportTime) entry.Collected[key] = currentValue return } if existing.ReportTime.Before(currentValue.ReportTime) { - level.Debug(s.logger).Log("msg", "Incrementing existing histogram", "fqName", currentValue.FqName, "key", key, "last_reported_time", existing.ReportTime, "incoming_time", currentValue.ReportTime) + s.logger.Debug("Incrementing existing histogram", "fqName", currentValue.FqName, "key", key, "last_reported_time", existing.ReportTime, "incoming_time", currentValue.ReportTime) currentValue.MergeHistogram(existing) // Replace the existing histogram by the new one after merging it. entry.Collected[key] = currentValue return } - level.Debug(s.logger).Log("msg", "Ignoring old sample for histogram", "fqName", currentValue.FqName, "key", key, "last_reported_time", existing.ReportTime, "incoming_time", currentValue.ReportTime) + s.logger.Debug("Ignoring old sample for histogram", "fqName", currentValue.FqName, "key", key, "last_reported_time", existing.ReportTime, "incoming_time", currentValue.ReportTime) } func toHistogramKey(hist *collectors.HistogramMetric) uint64 { @@ -119,7 +118,7 @@ func (s *InMemoryHistogramStore) ListMetrics(metricDescriptorName string) []*col for key, collected := range entry.Collected { // Scan and remove metrics which are outside the TTL if ttlWindowStart.After(collected.CollectionTime) { - level.Debug(s.logger).Log("msg", "Deleting histogram entry outside of TTL", "key", key, "fqName", collected.FqName) + s.logger.Debug("Deleting histogram entry outside of TTL", "key", key, "fqName", collected.FqName) delete(entry.Collected, key) continue } diff --git a/delta/histogram_test.go b/delta/histogram_test.go index 8c5cd00..35f7920 100644 --- a/delta/histogram_test.go +++ b/delta/histogram_test.go @@ -18,7 +18,7 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "github.com/prometheus/common/promlog" + "github.com/prometheus/common/promslog" "google.golang.org/api/monitoring/v3" "github.com/prometheus-community/stackdriver_exporter/collectors" @@ -33,7 +33,7 @@ var _ = Describe("HistogramStore", func() { bucketValue := uint64(1000) BeforeEach(func() { - store = delta.NewInMemoryHistogramStore(promlog.New(&promlog.Config{}), time.Minute) + store = delta.NewInMemoryHistogramStore(promslog.New(&promslog.Config{}), time.Minute) histogram = &collectors.HistogramMetric{ FqName: "histogram_name", LabelKeys: []string{"labelKey"}, diff --git a/go.mod b/go.mod index aa3690c..9339e10 100644 --- a/go.mod +++ b/go.mod @@ -1,17 +1,16 @@ module github.com/prometheus-community/stackdriver_exporter -go 1.21 +go 1.22 require ( github.com/PuerkitoBio/rehttp v1.4.0 github.com/alecthomas/kingpin/v2 v2.4.0 github.com/fatih/camelcase v1.0.0 - github.com/go-kit/log v0.2.1 github.com/onsi/ginkgo v1.16.5 github.com/onsi/gomega v1.34.1 - github.com/prometheus/client_golang v1.20.2 - github.com/prometheus/common v0.59.1 - github.com/prometheus/exporter-toolkit v0.11.0 + github.com/prometheus/client_golang v1.20.5 + github.com/prometheus/common v0.60.0 + github.com/prometheus/exporter-toolkit v0.13.0 golang.org/x/net v0.29.0 golang.org/x/oauth2 v0.23.0 google.golang.org/api v0.199.0 @@ -27,7 +26,6 @@ require ( github.com/coreos/go-systemd/v22 v22.5.0 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/fsnotify/fsnotify v1.4.9 // indirect - github.com/go-logfmt/logfmt v0.5.1 // indirect github.com/go-logr/logr v1.4.2 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect @@ -38,6 +36,8 @@ require ( github.com/googleapis/gax-go/v2 v2.13.0 // indirect github.com/jpillora/backoff v1.0.0 // indirect github.com/klauspost/compress v1.17.9 // indirect + github.com/mdlayher/socket v0.4.1 // indirect + github.com/mdlayher/vsock v1.2.1 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f // indirect github.com/nxadm/tail v1.4.8 // indirect diff --git a/go.sum b/go.sum index 546cdf9..ffdfe5d 100644 --- a/go.sum +++ b/go.sum @@ -40,10 +40,6 @@ github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSw github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= -github.com/go-kit/log v0.2.1 h1:MRVx0/zhvdseW+Gza6N9rVzU/IVzaeE1SFI4raAhmBU= -github.com/go-kit/log v0.2.1/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBjv0= -github.com/go-logfmt/logfmt v0.5.1 h1:otpy5pqBCBZ1ng9RQ0dPu4PN7ba75Y/aA+UpowDyNVA= -github.com/go-logfmt/logfmt v0.5.1/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= @@ -99,6 +95,10 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/mdlayher/socket v0.4.1 h1:eM9y2/jlbs1M615oshPQOHZzj6R6wMT7bX5NPiQvn2U= +github.com/mdlayher/socket v0.4.1/go.mod h1:cAqeGjoufqdxWkD7DkpyS+wcefOtmu5OQ8KuoJGIReA= +github.com/mdlayher/vsock v1.2.1 h1:pC1mTJTvjo1r9n9fbm7S1j04rCgCzhCOS5DY0zqHlnQ= +github.com/mdlayher/vsock v1.2.1/go.mod h1:NRfCibel++DgeMD8z/hP+PPTjlNJsdPOmxcnENvE+SE= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f h1:KUppIJq7/+SVif2QVs3tOP0zanoHgBEVAwHxUSIzRqU= @@ -118,15 +118,15 @@ github.com/onsi/gomega v1.34.1 h1:EUMJIKUjM8sKjYbtxQI9A4z2o+rruxnzNvpknOXie6k= github.com/onsi/gomega v1.34.1/go.mod h1:kU1QgUvBDLXBJq618Xvm2LUX6rSAfRaFRTcdOeDLwwY= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/prometheus/client_golang v1.20.2 h1:5ctymQzZlyOON1666svgwn3s6IKWgfbjsejTMiXIyjg= -github.com/prometheus/client_golang v1.20.2/go.mod h1:PIEt8X02hGcP8JWbeHyeZ53Y/jReSnHgO035n//V5WE= +github.com/prometheus/client_golang v1.20.5 h1:cxppBPuYhUnsO6yo/aoRol4L7q7UFfdm+bR9r+8l63Y= +github.com/prometheus/client_golang v1.20.5/go.mod h1:PIEt8X02hGcP8JWbeHyeZ53Y/jReSnHgO035n//V5WE= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E= github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY= -github.com/prometheus/common v0.59.1 h1:LXb1quJHWm1P6wq/U824uxYi4Sg0oGvNeUm1z5dJoX0= -github.com/prometheus/common v0.59.1/go.mod h1:GpWM7dewqmVYcd7SmRaiWVe9SSqjf0UrwnYnpEZNuT0= -github.com/prometheus/exporter-toolkit v0.11.0 h1:yNTsuZ0aNCNFQ3aFTD2uhPOvr4iD7fdBvKPAEGkNf+g= -github.com/prometheus/exporter-toolkit v0.11.0/go.mod h1:BVnENhnNecpwoTLiABx7mrPB/OLRIgN74qlQbV+FK1Q= +github.com/prometheus/common v0.60.0 h1:+V9PAREWNvJMAuJ1x1BaWl9dewMW4YrHZQbx0sJNllA= +github.com/prometheus/common v0.60.0/go.mod h1:h0LYf1R1deLSKtD4Vdg8gy4RuOvENW2J/h19V5NADQw= +github.com/prometheus/exporter-toolkit v0.13.0 h1:lmA0Q+8IaXgmFRKw09RldZmZdnvu9wwcDLIXGmTPw1c= +github.com/prometheus/exporter-toolkit v0.13.0/go.mod h1:2uop99EZl80KdXhv/MxVI2181fMcwlsumFOqBecGkG0= github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc= github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk= github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= diff --git a/stackdriver_exporter.go b/stackdriver_exporter.go index 7060144..0529f44 100644 --- a/stackdriver_exporter.go +++ b/stackdriver_exporter.go @@ -15,7 +15,7 @@ package main import ( "fmt" - stdlog "log" + "log/slog" "net/http" "os" "slices" @@ -23,13 +23,11 @@ import ( "github.com/PuerkitoBio/rehttp" "github.com/alecthomas/kingpin/v2" - "github.com/go-kit/log" - "github.com/go-kit/log/level" "github.com/prometheus/client_golang/prometheus" versioncollector "github.com/prometheus/client_golang/prometheus/collectors/version" "github.com/prometheus/client_golang/prometheus/promhttp" - "github.com/prometheus/common/promlog" - "github.com/prometheus/common/promlog/flag" + "github.com/prometheus/common/promslog" + "github.com/prometheus/common/promslog/flag" "github.com/prometheus/common/version" "github.com/prometheus/exporter-toolkit/web" webflag "github.com/prometheus/exporter-toolkit/web/kingpinflag" @@ -180,7 +178,7 @@ func createMonitoringService(ctx context.Context) (*monitoring.Service, error) { type handler struct { handler http.Handler - logger log.Logger + logger *slog.Logger projectIDs []string metricsPrefixes []string @@ -204,7 +202,7 @@ func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { h.handler.ServeHTTP(w, r) } -func newHandler(projectIDs []string, metricPrefixes []string, metricExtraFilters []collectors.MetricFilter, m *monitoring.Service, logger log.Logger, additionalGatherer prometheus.Gatherer) *handler { +func newHandler(projectIDs []string, metricPrefixes []string, metricExtraFilters []collectors.MetricFilter, m *monitoring.Service, logger *slog.Logger, additionalGatherer prometheus.Gatherer) *handler { h := &handler{ logger: logger, projectIDs: projectIDs, @@ -235,7 +233,7 @@ func (h *handler) innerHandler(filters map[string]bool) http.Handler { DescriptorCacheOnlyGoogle: *monitoringDescriptorCacheOnlyGoogle, }, h.logger, delta.NewInMemoryCounterStore(h.logger, *monitoringMetricsDeltasTTL), delta.NewInMemoryHistogramStore(h.logger, *monitoringMetricsDeltasTTL)) if err != nil { - level.Error(h.logger).Log("err", err) + h.logger.Error("error creating monitoring collector", "err", err) os.Exit(1) } registry.MustRegister(monitoringCollector) @@ -247,7 +245,7 @@ func (h *handler) innerHandler(filters map[string]bool) http.Handler { registry, } } - opts := promhttp.HandlerOpts{ErrorLog: stdlog.New(log.NewStdlibAdapter(level.Error(h.logger)), "", 0)} + opts := promhttp.HandlerOpts{ErrorLog: slog.NewLogLogger(h.logger.Handler(), slog.LevelError)} // Delegate http serving to Prometheus client library, which will call collector.Collect. return promhttp.HandlerFor(gatherers, opts) } @@ -268,22 +266,22 @@ func (h *handler) filterMetricTypePrefixes(filters map[string]bool) []string { } func main() { - promlogConfig := &promlog.Config{} - flag.AddFlags(kingpin.CommandLine, promlogConfig) + promslogConfig := &promslog.Config{} + flag.AddFlags(kingpin.CommandLine, promslogConfig) kingpin.Version(version.Print("stackdriver_exporter")) kingpin.HelpFlag.Short('h') kingpin.Parse() - logger := promlog.New(promlogConfig) + logger := promslog.New(promslogConfig) if *projectID != "" { - level.Warn(logger).Log("msg", "The google.project-id flag is deprecated and will be replaced by google.project-ids.") + logger.Warn("The google.project-id flag is deprecated and will be replaced by google.project-ids.") } if *monitoringMetricsTypePrefixes != "" { - level.Warn(logger).Log("msg", "The monitoring.metrics-type-prefixes flag is deprecated and will be replaced by monitoring.metrics-prefix.") + logger.Warn("The monitoring.metrics-type-prefixes flag is deprecated and will be replaced by monitoring.metrics-prefix.") } if *monitoringMetricsTypePrefixes == "" && len(*monitoringMetricsPrefixes) == 0 { - level.Error(logger).Log("msg", "At least one GCP monitoring prefix is required.") + logger.Error("At least one GCP monitoring prefix is required.") os.Exit(1) } @@ -291,11 +289,11 @@ func main() { var discoveredProjectIDs []string if len(*projectIDs) == 0 && *projectID == "" && *projectsFilter == "" { - level.Info(logger).Log("msg", "Neither projectIDs nor projectsFilter was provided. Trying to discover it") + logger.Info("Neither projectIDs nor projectsFilter was provided. Trying to discover it") var err error defaultProject, err := getDefaultGCPProject(ctx) if err != nil { - level.Error(logger).Log("msg", "no explicit projectIDs and error trying to discover default GCloud project", "err", err) + logger.Error("no explicit projectIDs and error trying to discover default GCloud project", "err", err) os.Exit(1) } discoveredProjectIDs = append(discoveredProjectIDs, *defaultProject) @@ -303,14 +301,14 @@ func main() { monitoringService, err := createMonitoringService(ctx) if err != nil { - level.Error(logger).Log("msg", "failed to create monitoring service", "err", err) + logger.Error("failed to create monitoring service", "err", err) os.Exit(1) } if *projectsFilter != "" { projectIDsFromFilter, err := utils.GetProjectIDsFromFilter(ctx, *projectsFilter) if err != nil { - level.Error(logger).Log("msg", "failed to get project IDs from filter", "err", err) + logger.Error("failed to get project IDs from filter", "err", err) os.Exit(1) } discoveredProjectIDs = append(discoveredProjectIDs, projectIDsFromFilter...) @@ -331,8 +329,8 @@ func main() { metricsPrefixes = append(metricsPrefixes, strings.Split(*monitoringMetricsTypePrefixes, ",")...) } - level.Info(logger).Log( - "msg", "Starting stackdriver_exporter", + logger.Info( + "Starting stackdriver_exporter", "version", version.Info(), "build_context", version.BuildContext(), "metric_prefixes", fmt.Sprintf("%v", metricsPrefixes), @@ -352,7 +350,7 @@ func main() { uniqueProjectIds, parsedMetricsPrefixes, metricExtraFilters, monitoringService, logger, prometheus.DefaultGatherer) http.Handle(*metricsPath, promhttp.InstrumentMetricHandler(prometheus.DefaultRegisterer, handler)) } else { - level.Info(logger).Log("msg", "Serving Stackdriver metrics at separate path", "path", *stackdriverMetricsPath) + logger.Info("Serving Stackdriver metrics at separate path", "path", *stackdriverMetricsPath) handler := newHandler( uniqueProjectIds, parsedMetricsPrefixes, metricExtraFilters, monitoringService, logger, nil) http.Handle(*stackdriverMetricsPath, promhttp.InstrumentMetricHandler(prometheus.DefaultRegisterer, handler)) @@ -381,7 +379,7 @@ func main() { } landingPage, err := web.NewLandingPage(landingConfig) if err != nil { - level.Error(logger).Log("err", err) + logger.Error("error creating landing page", "err", err) os.Exit(1) } http.Handle("/", landingPage) @@ -389,7 +387,7 @@ func main() { srv := &http.Server{} if err := web.ListenAndServe(srv, toolkitFlags, logger); err != nil { - level.Error(logger).Log("msg", "Error starting server", "err", err) + logger.Error("Error starting server", "err", err) os.Exit(1) } }