From 356d2c05d66d7dc87655da242d60d50e5a5691bf Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Tue, 5 Nov 2024 08:18:05 +0100 Subject: [PATCH] [chore]: enable perfsprint linter for receivers Signed-off-by: Matthieu MOREL --- receiver/aerospikereceiver/client.go | 3 +- receiver/apachesparkreceiver/scraper.go | 72 +++++++++---------- .../internal/cadvisor/extractors/extractor.go | 4 +- .../internal/ecsInfo/cgroup.go | 3 +- .../internal/k8sapiserver/k8sapiserver.go | 8 +-- .../internal/stores/podstore.go | 4 +- .../stats_provider_test.go | 4 +- .../receiver_test.go | 3 +- receiver/awsfirehosereceiver/config_test.go | 3 +- .../nop_logs_unmarshaler_test.go | 4 +- .../nop_metrics_unmarshaler_test.go | 4 +- receiver/awsfirehosereceiver/receiver.go | 3 +- receiver/awsfirehosereceiver/receiver_test.go | 3 +- receiver/awss3receiver/notifications_test.go | 8 +-- receiver/awss3receiver/s3reader_test.go | 2 +- .../internal/translator/translator_test.go | 8 +-- receiver/chronyreceiver/config_test.go | 3 +- .../internal/chrony/client_test.go | 2 +- .../internal/chrony/util_test.go | 3 +- receiver/cloudflarereceiver/logs.go | 4 +- receiver/couchdbreceiver/metrics.go | 10 +-- .../internal/translator/tags.go | 3 +- .../translator/traces_translator_test.go | 8 +-- receiver/datadogreceiver/receiver.go | 4 +- receiver/dockerstatsreceiver/receiver.go | 2 +- receiver/elasticsearchreceiver/client.go | 4 +- receiver/expvarreceiver/config.go | 3 +- receiver/expvarreceiver/scraper.go | 3 +- receiver/filelogreceiver/filelog_test.go | 5 +- receiver/flinkmetricsreceiver/client.go | 3 +- .../googlecloudmonitoringreceiver/receiver.go | 2 +- .../internal/handler.go | 2 +- .../internal/metadata/metricsdatapoint.go | 8 +-- .../metadata/metricsdatapoint_test.go | 6 +- .../perfcounter_scraper_errors.go | 3 +- receiver/jaegerreceiver/config.go | 9 +-- receiver/jaegerreceiver/trace_receiver.go | 2 +- receiver/jmxreceiver/config.go | 2 +- .../internal/subprocess/subprocess.go | 3 +- receiver/jmxreceiver/receiver.go | 4 +- .../internal/metadata/metadata.go | 5 +- .../k8sclusterreceiver/internal/node/nodes.go | 4 +- receiver/k8sclusterreceiver/receiver.go | 3 +- receiver/k8sobjectsreceiver/config.go | 3 +- receiver/k8sobjectsreceiver/receiver.go | 3 +- .../broker_scraper_test.go | 6 +- .../consumer_scraper_test.go | 8 +-- .../kafkametricsreceiver/receiver_test.go | 6 +- .../scraper_test_helper.go | 22 +++--- .../topic_scraper_test.go | 6 +- receiver/kafkareceiver/factory.go | 4 +- receiver/kafkareceiver/header_extraction.go | 4 +- receiver/kafkareceiver/kafka_receiver.go | 3 +- .../internal/mongodb_atlas_client.go | 11 +-- receiver/mongodbreceiver/config.go | 2 +- .../otelarrowreceiver/internal/arrow/arrow.go | 9 ++- .../internal/arrow/arrow_test.go | 11 +-- receiver/otelarrowreceiver/otelarrow_test.go | 8 +-- receiver/podmanreceiver/libpod_client.go | 2 +- receiver/podmanreceiver/libpod_client_test.go | 9 ++- receiver/podmanreceiver/podman_test.go | 5 +- receiver/postgresqlreceiver/client.go | 2 +- receiver/postgresqlreceiver/scraper_test.go | 7 +- .../prometheusreceiver/metrics_receiver.go | 2 +- ...trics_receiver_scrape_config_files_test.go | 5 +- .../targetallocator/config.go | 3 +- .../targetallocator/manager.go | 2 +- receiver/receivercreator/consumer.go | 7 +- receiver/receivercreator/receiver.go | 3 +- receiver/sapmreceiver/factory.go | 3 +- receiver/signalfxreceiver/factory.go | 3 +- receiver/skywalkingreceiver/config.go | 5 +- receiver/skywalkingreceiver/factory.go | 3 +- receiver/snmpreceiver/client_test.go | 12 ++-- .../solacereceiver/messaging_service_test.go | 10 +-- receiver/solacereceiver/receiver.go | 3 +- receiver/solacereceiver/receiver_test.go | 9 ++- .../unmarshaller_egress_test.go | 4 +- receiver/splunkhecreceiver/receiver_test.go | 6 +- receiver/sqlserverreceiver/config.go | 4 +- receiver/sqlserverreceiver/scraper_test.go | 4 +- .../internal/configssh/configssh.go | 4 +- .../internal/configssh/configssh_test.go | 6 +- receiver/sshcheckreceiver/scraper_test.go | 5 +- receiver/statsdreceiver/config.go | 9 +-- .../internal/protocol/statsd_parser.go | 2 +- receiver/vcenterreceiver/processors.go | 4 +- receiver/vcenterreceiver/scraper.go | 2 +- .../receiver_others.go | 4 +- .../windowsperfcountersreceiver/config.go | 7 +- .../config_test.go | 2 +- receiver/zookeeperreceiver/scraper.go | 2 +- receiver/zookeeperreceiver/scraper_test.go | 3 +- 93 files changed, 258 insertions(+), 257 deletions(-) diff --git a/receiver/aerospikereceiver/client.go b/receiver/aerospikereceiver/client.go index 1e6fc0cd90a0..0221a92de061 100644 --- a/receiver/aerospikereceiver/client.go +++ b/receiver/aerospikereceiver/client.go @@ -5,7 +5,6 @@ package aerospikereceiver // import "github.com/open-telemetry/opentelemetry-col import ( "crypto/tls" - "fmt" "strings" "sync" "time" @@ -266,7 +265,7 @@ func allNamespaceInfo(n cluster.Node, policy *as.InfoPolicy) (metricsMap, error) commands := make([]string, len(names)) for i, name := range names { - commands[i] = fmt.Sprintf("namespace/%s", name) + commands[i] = "namespace/" + name } res, err = n.RequestInfo(policy, commands...) diff --git a/receiver/apachesparkreceiver/scraper.go b/receiver/apachesparkreceiver/scraper.go index 2fb431e6c246..a33dd27754d2 100644 --- a/receiver/apachesparkreceiver/scraper.go +++ b/receiver/apachesparkreceiver/scraper.go @@ -126,122 +126,122 @@ func (s *sparkScraper) scrape(_ context.Context) (pmetric.Metrics, error) { } func (s *sparkScraper) recordCluster(clusterStats *models.ClusterProperties, now pcommon.Timestamp, appID string, appName string) { - if stat, ok := clusterStats.Gauges[fmt.Sprintf("%s.driver.BlockManager.disk.diskSpaceUsed_MB", appID)]; ok { + if stat, ok := clusterStats.Gauges[appID+".driver.BlockManager.disk.diskSpaceUsed_MB"]; ok { s.mb.RecordSparkDriverBlockManagerDiskUsageDataPoint(now, int64(stat.Value)) } - if stat, ok := clusterStats.Gauges[fmt.Sprintf("%s.driver.BlockManager.memory.offHeapMemUsed_MB", appID)]; ok { + if stat, ok := clusterStats.Gauges[appID+".driver.BlockManager.memory.offHeapMemUsed_MB"]; ok { s.mb.RecordSparkDriverBlockManagerMemoryUsageDataPoint(now, int64(stat.Value), metadata.AttributeLocationOffHeap, metadata.AttributeStateUsed) } - if stat, ok := clusterStats.Gauges[fmt.Sprintf("%s.driver.BlockManager.memory.onHeapMemUsed_MB", appID)]; ok { + if stat, ok := clusterStats.Gauges[appID+".driver.BlockManager.memory.onHeapMemUsed_MB"]; ok { s.mb.RecordSparkDriverBlockManagerMemoryUsageDataPoint(now, int64(stat.Value), metadata.AttributeLocationOnHeap, metadata.AttributeStateUsed) } - if stat, ok := clusterStats.Gauges[fmt.Sprintf("%s.driver.BlockManager.memory.remainingOffHeapMem_MB", appID)]; ok { + if stat, ok := clusterStats.Gauges[appID+".driver.BlockManager.memory.remainingOffHeapMem_MB"]; ok { s.mb.RecordSparkDriverBlockManagerMemoryUsageDataPoint(now, int64(stat.Value), metadata.AttributeLocationOffHeap, metadata.AttributeStateFree) } - if stat, ok := clusterStats.Gauges[fmt.Sprintf("%s.driver.BlockManager.memory.remainingOnHeapMem_MB", appID)]; ok { + if stat, ok := clusterStats.Gauges[appID+".driver.BlockManager.memory.remainingOnHeapMem_MB"]; ok { s.mb.RecordSparkDriverBlockManagerMemoryUsageDataPoint(now, int64(stat.Value), metadata.AttributeLocationOnHeap, metadata.AttributeStateFree) } - if stat, ok := clusterStats.Counters[fmt.Sprintf("%s.driver.HiveExternalCatalog.fileCacheHits", appID)]; ok { + if stat, ok := clusterStats.Counters[appID+".driver.HiveExternalCatalog.fileCacheHits"]; ok { s.mb.RecordSparkDriverHiveExternalCatalogFileCacheHitsDataPoint(now, stat.Count) } - if stat, ok := clusterStats.Counters[fmt.Sprintf("%s.driver.HiveExternalCatalog.filesDiscovered", appID)]; ok { + if stat, ok := clusterStats.Counters[appID+".driver.HiveExternalCatalog.filesDiscovered"]; ok { s.mb.RecordSparkDriverHiveExternalCatalogFilesDiscoveredDataPoint(now, stat.Count) } - if stat, ok := clusterStats.Counters[fmt.Sprintf("%s.driver.HiveExternalCatalog.hiveClientCalls", appID)]; ok { + if stat, ok := clusterStats.Counters[appID+".driver.HiveExternalCatalog.hiveClientCalls"]; ok { s.mb.RecordSparkDriverHiveExternalCatalogHiveClientCallsDataPoint(now, stat.Count) } - if stat, ok := clusterStats.Counters[fmt.Sprintf("%s.driver.HiveExternalCatalog.parallelListingJobCount", appID)]; ok { + if stat, ok := clusterStats.Counters[appID+".driver.HiveExternalCatalog.parallelListingJobCount"]; ok { s.mb.RecordSparkDriverHiveExternalCatalogParallelListingJobsDataPoint(now, stat.Count) } - if stat, ok := clusterStats.Counters[fmt.Sprintf("%s.driver.HiveExternalCatalog.partitionsFetched", appID)]; ok { + if stat, ok := clusterStats.Counters[appID+".driver.HiveExternalCatalog.partitionsFetched"]; ok { s.mb.RecordSparkDriverHiveExternalCatalogPartitionsFetchedDataPoint(now, stat.Count) } - if stat, ok := clusterStats.Histograms[fmt.Sprintf("%s.driver.CodeGenerator.compilationTime", appID)]; ok { + if stat, ok := clusterStats.Histograms[appID+".driver.CodeGenerator.compilationTime"]; ok { s.mb.RecordSparkDriverCodeGeneratorCompilationCountDataPoint(now, stat.Count) s.mb.RecordSparkDriverCodeGeneratorCompilationAverageTimeDataPoint(now, stat.Mean) } - if stat, ok := clusterStats.Histograms[fmt.Sprintf("%s.driver.CodeGenerator.generatedClassSize", appID)]; ok { + if stat, ok := clusterStats.Histograms[appID+".driver.CodeGenerator.generatedClassSize"]; ok { s.mb.RecordSparkDriverCodeGeneratorGeneratedClassCountDataPoint(now, stat.Count) s.mb.RecordSparkDriverCodeGeneratorGeneratedClassAverageSizeDataPoint(now, stat.Mean) } - if stat, ok := clusterStats.Histograms[fmt.Sprintf("%s.driver.CodeGenerator.generatedMethodSize", appID)]; ok { + if stat, ok := clusterStats.Histograms[appID+".driver.CodeGenerator.generatedMethodSize"]; ok { s.mb.RecordSparkDriverCodeGeneratorGeneratedMethodCountDataPoint(now, stat.Count) s.mb.RecordSparkDriverCodeGeneratorGeneratedMethodAverageSizeDataPoint(now, stat.Mean) } - if stat, ok := clusterStats.Histograms[fmt.Sprintf("%s.driver.CodeGenerator.sourceCodeSize", appID)]; ok { + if stat, ok := clusterStats.Histograms[appID+".driver.CodeGenerator.sourceCodeSize"]; ok { s.mb.RecordSparkDriverCodeGeneratorSourceCodeOperationsDataPoint(now, stat.Count) s.mb.RecordSparkDriverCodeGeneratorSourceCodeAverageSizeDataPoint(now, stat.Mean) } - if stat, ok := clusterStats.Gauges[fmt.Sprintf("%s.driver.DAGScheduler.job.activeJobs", appID)]; ok { + if stat, ok := clusterStats.Gauges[appID+".driver.DAGScheduler.job.activeJobs"]; ok { s.mb.RecordSparkDriverDagSchedulerJobActiveDataPoint(now, int64(stat.Value)) } - if stat, ok := clusterStats.Gauges[fmt.Sprintf("%s.driver.DAGScheduler.job.allJobs", appID)]; ok { + if stat, ok := clusterStats.Gauges[appID+".driver.DAGScheduler.job.allJobs"]; ok { s.mb.RecordSparkDriverDagSchedulerJobCountDataPoint(now, int64(stat.Value)) } - if stat, ok := clusterStats.Gauges[fmt.Sprintf("%s.driver.DAGScheduler.stage.failedStages", appID)]; ok { + if stat, ok := clusterStats.Gauges[appID+".driver.DAGScheduler.stage.failedStages"]; ok { s.mb.RecordSparkDriverDagSchedulerStageFailedDataPoint(now, int64(stat.Value)) } - if stat, ok := clusterStats.Gauges[fmt.Sprintf("%s.driver.DAGScheduler.stage.runningStages", appID)]; ok { + if stat, ok := clusterStats.Gauges[appID+".driver.DAGScheduler.stage.runningStages"]; ok { s.mb.RecordSparkDriverDagSchedulerStageCountDataPoint(now, int64(stat.Value), metadata.AttributeSchedulerStatusRunning) } - if stat, ok := clusterStats.Gauges[fmt.Sprintf("%s.driver.DAGScheduler.stage.waitingStages", appID)]; ok { + if stat, ok := clusterStats.Gauges[appID+".driver.DAGScheduler.stage.waitingStages"]; ok { s.mb.RecordSparkDriverDagSchedulerStageCountDataPoint(now, int64(stat.Value), metadata.AttributeSchedulerStatusWaiting) } - if stat, ok := clusterStats.Counters[fmt.Sprintf("%s.driver.LiveListenerBus.numEventsPosted", appID)]; ok { + if stat, ok := clusterStats.Counters[appID+".driver.LiveListenerBus.numEventsPosted"]; ok { s.mb.RecordSparkDriverLiveListenerBusPostedDataPoint(now, stat.Count) } - if stat, ok := clusterStats.Timers[fmt.Sprintf("%s.driver.LiveListenerBus.queue.appStatus.listenerProcessingTime", appID)]; ok { + if stat, ok := clusterStats.Timers[appID+".driver.LiveListenerBus.queue.appStatus.listenerProcessingTime"]; ok { s.mb.RecordSparkDriverLiveListenerBusProcessingTimeAverageDataPoint(now, stat.Mean) } - if stat, ok := clusterStats.Counters[fmt.Sprintf("%s.driver.LiveListenerBus.queue.appStatus.numDroppedEvents", appID)]; ok { + if stat, ok := clusterStats.Counters[appID+".driver.LiveListenerBus.queue.appStatus.numDroppedEvents"]; ok { s.mb.RecordSparkDriverLiveListenerBusDroppedDataPoint(now, stat.Count) } - if stat, ok := clusterStats.Gauges[fmt.Sprintf("%s.driver.LiveListenerBus.queue.appStatus.size", appID)]; ok { + if stat, ok := clusterStats.Gauges[appID+".driver.LiveListenerBus.queue.appStatus.size"]; ok { s.mb.RecordSparkDriverLiveListenerBusQueueSizeDataPoint(now, int64(stat.Value)) } - if stat, ok := clusterStats.Gauges[fmt.Sprintf("%s.driver.JVMCPU.jvmCpuTime", appID)]; ok { + if stat, ok := clusterStats.Gauges[appID+".driver.JVMCPU.jvmCpuTime"]; ok { s.mb.RecordSparkDriverJvmCPUTimeDataPoint(now, int64(stat.Value)) } - if stat, ok := clusterStats.Gauges[fmt.Sprintf("%s.driver.ExecutorMetrics.JVMOffHeapMemory", appID)]; ok { + if stat, ok := clusterStats.Gauges[appID+".driver.ExecutorMetrics.JVMOffHeapMemory"]; ok { s.mb.RecordSparkDriverExecutorMemoryJvmDataPoint(now, int64(stat.Value), metadata.AttributeLocationOffHeap) } - if stat, ok := clusterStats.Gauges[fmt.Sprintf("%s.driver.ExecutorMetrics.JVMHeapMemory", appID)]; ok { + if stat, ok := clusterStats.Gauges[appID+".driver.ExecutorMetrics.JVMHeapMemory"]; ok { s.mb.RecordSparkDriverExecutorMemoryJvmDataPoint(now, int64(stat.Value), metadata.AttributeLocationOnHeap) } - if stat, ok := clusterStats.Gauges[fmt.Sprintf("%s.driver.ExecutorMetrics.OffHeapExecutionMemory", appID)]; ok { + if stat, ok := clusterStats.Gauges[appID+".driver.ExecutorMetrics.OffHeapExecutionMemory"]; ok { s.mb.RecordSparkDriverExecutorMemoryExecutionDataPoint(now, int64(stat.Value), metadata.AttributeLocationOffHeap) } - if stat, ok := clusterStats.Gauges[fmt.Sprintf("%s.driver.ExecutorMetrics.OnHeapExecutionMemory", appID)]; ok { + if stat, ok := clusterStats.Gauges[appID+".driver.ExecutorMetrics.OnHeapExecutionMemory"]; ok { s.mb.RecordSparkDriverExecutorMemoryExecutionDataPoint(now, int64(stat.Value), metadata.AttributeLocationOnHeap) } - if stat, ok := clusterStats.Gauges[fmt.Sprintf("%s.driver.ExecutorMetrics.OffHeapStorageMemory", appID)]; ok { + if stat, ok := clusterStats.Gauges[appID+".driver.ExecutorMetrics.OffHeapStorageMemory"]; ok { s.mb.RecordSparkDriverExecutorMemoryStorageDataPoint(now, int64(stat.Value), metadata.AttributeLocationOffHeap) } - if stat, ok := clusterStats.Gauges[fmt.Sprintf("%s.driver.ExecutorMetrics.OnHeapStorageMemory", appID)]; ok { + if stat, ok := clusterStats.Gauges[appID+".driver.ExecutorMetrics.OnHeapStorageMemory"]; ok { s.mb.RecordSparkDriverExecutorMemoryStorageDataPoint(now, int64(stat.Value), metadata.AttributeLocationOnHeap) } - if stat, ok := clusterStats.Gauges[fmt.Sprintf("%s.driver.ExecutorMetrics.DirectPoolMemory", appID)]; ok { + if stat, ok := clusterStats.Gauges[appID+".driver.ExecutorMetrics.DirectPoolMemory"]; ok { s.mb.RecordSparkDriverExecutorMemoryPoolDataPoint(now, int64(stat.Value), metadata.AttributePoolMemoryTypeDirect) } - if stat, ok := clusterStats.Gauges[fmt.Sprintf("%s.driver.ExecutorMetrics.MappedPoolMemory", appID)]; ok { + if stat, ok := clusterStats.Gauges[appID+".driver.ExecutorMetrics.MappedPoolMemory"]; ok { s.mb.RecordSparkDriverExecutorMemoryPoolDataPoint(now, int64(stat.Value), metadata.AttributePoolMemoryTypeMapped) } - if stat, ok := clusterStats.Gauges[fmt.Sprintf("%s.driver.ExecutorMetrics.MinorGCCount", appID)]; ok { + if stat, ok := clusterStats.Gauges[appID+".driver.ExecutorMetrics.MinorGCCount"]; ok { s.mb.RecordSparkDriverExecutorGcOperationsDataPoint(now, int64(stat.Value), metadata.AttributeGcTypeMinor) } - if stat, ok := clusterStats.Gauges[fmt.Sprintf("%s.driver.ExecutorMetrics.MajorGCCount", appID)]; ok { + if stat, ok := clusterStats.Gauges[appID+".driver.ExecutorMetrics.MajorGCCount"]; ok { s.mb.RecordSparkDriverExecutorGcOperationsDataPoint(now, int64(stat.Value), metadata.AttributeGcTypeMajor) } - if stat, ok := clusterStats.Gauges[fmt.Sprintf("%s.driver.ExecutorMetrics.MinorGCTime", appID)]; ok { + if stat, ok := clusterStats.Gauges[appID+".driver.ExecutorMetrics.MinorGCTime"]; ok { s.mb.RecordSparkDriverExecutorGcTimeDataPoint(now, int64(stat.Value), metadata.AttributeGcTypeMinor) } - if stat, ok := clusterStats.Gauges[fmt.Sprintf("%s.driver.ExecutorMetrics.MajorGCTime", appID)]; ok { + if stat, ok := clusterStats.Gauges[appID+".driver.ExecutorMetrics.MajorGCTime"]; ok { s.mb.RecordSparkDriverExecutorGcTimeDataPoint(now, int64(stat.Value), metadata.AttributeGcTypeMajor) } diff --git a/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/extractor.go b/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/extractor.go index 398ad4805a59..18bb1a91e435 100644 --- a/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/extractor.go +++ b/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/extractor.go @@ -164,10 +164,10 @@ func getMetricKey(metric *CAdvisorMetric) string { switch metricType { case ci.TypeInstance: // merge cpu, memory, net metric for type Instance - metricKey = fmt.Sprintf("metricType:%s", ci.TypeInstance) + metricKey = "metricType:" + ci.TypeInstance case ci.TypeNode: // merge cpu, memory, net metric for type Node - metricKey = fmt.Sprintf("metricType:%s", ci.TypeNode) + metricKey = "metricType:" + ci.TypeNode case ci.TypePod: // merge cpu, memory, net metric for type Pod metricKey = fmt.Sprintf("metricType:%s,podId:%s", ci.TypePod, metric.GetTags()[ci.PodIDKey]) diff --git a/receiver/awscontainerinsightreceiver/internal/ecsInfo/cgroup.go b/receiver/awscontainerinsightreceiver/internal/ecsInfo/cgroup.go index cce6b10419f6..b99339bfda59 100644 --- a/receiver/awscontainerinsightreceiver/internal/ecsInfo/cgroup.go +++ b/receiver/awscontainerinsightreceiver/internal/ecsInfo/cgroup.go @@ -6,6 +6,7 @@ package ecsinfo // import "github.com/open-telemetry/opentelemetry-collector-con import ( "bufio" "context" + "errors" "fmt" "log" "math" @@ -227,7 +228,7 @@ func getCGroupMountPoint(mountConfigPath string) (string, error) { return filepath.Dir(fields[4]), nil } } - return "", fmt.Errorf("mount point not existed") + return "", errors.New("mount point not existed") } func getCGroupPathForTask(cgroupMount, controller, taskID, clusterName string) (string, error) { diff --git a/receiver/awscontainerinsightreceiver/internal/k8sapiserver/k8sapiserver.go b/receiver/awscontainerinsightreceiver/internal/k8sapiserver/k8sapiserver.go index c64912388264..4477a27bba13 100644 --- a/receiver/awscontainerinsightreceiver/internal/k8sapiserver/k8sapiserver.go +++ b/receiver/awscontainerinsightreceiver/internal/k8sapiserver/k8sapiserver.go @@ -260,7 +260,7 @@ func (k *K8sAPIServer) startLeaderElection(ctx context.Context, lock resourceloc RetryPeriod: 5 * time.Second, Callbacks: leaderelection.LeaderCallbacks{ OnStartedLeading: func(ctx context.Context) { - k.logger.Info(fmt.Sprintf("k8sapiserver OnStartedLeading: %s", k.nodeName)) + k.logger.Info("k8sapiserver OnStartedLeading: " + k.nodeName) // we're notified when we start k.mu.Lock() k.leading = true @@ -292,7 +292,7 @@ func (k *K8sAPIServer) startLeaderElection(ctx context.Context, lock resourceloc } }, OnStoppedLeading: func() { - k.logger.Info(fmt.Sprintf("k8sapiserver OnStoppedLeading: %s", k.nodeName)) + k.logger.Info("k8sapiserver OnStoppedLeading: " + k.nodeName) // we can do cleanup here, or after the RunOrDie method returns k.mu.Lock() defer k.mu.Unlock() @@ -302,14 +302,14 @@ func (k *K8sAPIServer) startLeaderElection(ctx context.Context, lock resourceloc k.k8sClient.ShutdownPodClient() }, OnNewLeader: func(identity string) { - k.logger.Info(fmt.Sprintf("k8sapiserver Switch New Leader: %s", identity)) + k.logger.Info("k8sapiserver Switch New Leader: " + identity) }, }, }) select { case <-ctx.Done(): // when leader election ends, the channel ctx.Done() will be closed - k.logger.Info(fmt.Sprintf("k8sapiserver shutdown Leader Election: %s", k.nodeName)) + k.logger.Info("k8sapiserver shutdown Leader Election: " + k.nodeName) return default: } diff --git a/receiver/awscontainerinsightreceiver/internal/stores/podstore.go b/receiver/awscontainerinsightreceiver/internal/stores/podstore.go index bf464069a349..e6027d2dd54a 100644 --- a/receiver/awscontainerinsightreceiver/internal/stores/podstore.go +++ b/receiver/awscontainerinsightreceiver/internal/stores/podstore.go @@ -217,7 +217,7 @@ func (p *PodStore) Decorate(ctx context.Context, metric CIMetric, kubernetesBlob p.addPodOwnersAndPodName(metric, &entry.pod, kubernetesBlob) addLabels(&entry.pod, kubernetesBlob) } else { - p.logger.Warn(fmt.Sprintf("no pod information is found in podstore for pod %s", podKey)) + p.logger.Warn("no pod information is found in podstore for pod " + podKey) return false } } @@ -262,7 +262,7 @@ func (p *PodStore) refreshInternal(now time.Time, podList []corev1.Pod) { pod := podList[i] podKey := createPodKeyFromMetaData(&pod) if podKey == "" { - p.logger.Warn(fmt.Sprintf("podKey is unavailable, refresh pod store for pod %s", pod.Name)) + p.logger.Warn("podKey is unavailable, refresh pod store for pod " + pod.Name) continue } if pod.Status.Phase != corev1.PodSucceeded && pod.Status.Phase != corev1.PodFailed { diff --git a/receiver/awsecscontainermetricsreceiver/internal/awsecscontainermetrics/stats_provider_test.go b/receiver/awsecscontainermetricsreceiver/internal/awsecscontainermetrics/stats_provider_test.go index 3684dd9eccb2..e5ce59c85942 100644 --- a/receiver/awsecscontainermetricsreceiver/internal/awsecscontainermetrics/stats_provider_test.go +++ b/receiver/awsecscontainermetricsreceiver/internal/awsecscontainermetrics/stats_provider_test.go @@ -4,7 +4,7 @@ package awsecscontainermetrics import ( - "fmt" + "errors" "os" "testing" @@ -28,7 +28,7 @@ func (f testRestClient) GetResponse(path string) ([]byte, error) { } if f.fail { - return []byte{}, fmt.Errorf("failed") + return []byte{}, errors.New("failed") } if f.invalidJSON { return []byte("wrong-json-body"), nil diff --git a/receiver/awsecscontainermetricsreceiver/receiver_test.go b/receiver/awsecscontainermetricsreceiver/receiver_test.go index ecfcf88cd218..4ee3f7752126 100644 --- a/receiver/awsecscontainermetricsreceiver/receiver_test.go +++ b/receiver/awsecscontainermetricsreceiver/receiver_test.go @@ -6,7 +6,6 @@ package awsecscontainermetricsreceiver import ( "context" "errors" - "fmt" "os" "testing" @@ -96,7 +95,7 @@ type invalidFakeClient struct { } func (f invalidFakeClient) GetResponse(_ string) ([]byte, error) { - return nil, fmt.Errorf("intentional error") + return nil, errors.New("intentional error") } func TestCollectDataFromEndpointWithEndpointError(t *testing.T) { diff --git a/receiver/awsfirehosereceiver/config_test.go b/receiver/awsfirehosereceiver/config_test.go index 9f5f89850dc4..5d9429ddc62b 100644 --- a/receiver/awsfirehosereceiver/config_test.go +++ b/receiver/awsfirehosereceiver/config_test.go @@ -4,7 +4,6 @@ package awsfirehosereceiver import ( - "fmt" "path/filepath" "testing" @@ -23,7 +22,7 @@ func TestLoadConfig(t *testing.T) { "cwmetrics", "cwlogs", "otlp_v1", "invalid", } { t.Run(configType, func(t *testing.T) { - fileName := fmt.Sprintf("%s_config.yaml", configType) + fileName := configType + "_config.yaml" cm, err := confmaptest.LoadConf(filepath.Join("testdata", fileName)) require.NoError(t, err) diff --git a/receiver/awsfirehosereceiver/internal/unmarshaler/unmarshalertest/nop_logs_unmarshaler_test.go b/receiver/awsfirehosereceiver/internal/unmarshaler/unmarshalertest/nop_logs_unmarshaler_test.go index 69be0c74f224..ce90c351cfbd 100644 --- a/receiver/awsfirehosereceiver/internal/unmarshaler/unmarshalertest/nop_logs_unmarshaler_test.go +++ b/receiver/awsfirehosereceiver/internal/unmarshaler/unmarshalertest/nop_logs_unmarshaler_test.go @@ -4,7 +4,7 @@ package unmarshalertest import ( - "fmt" + "errors" "testing" "github.com/stretchr/testify/require" @@ -31,7 +31,7 @@ func TestNewWithLogs(t *testing.T) { } func TestNewErrLogs(t *testing.T) { - wantErr := fmt.Errorf("test error") + wantErr := errors.New("test error") unmarshaler := NewErrLogs(wantErr) got, err := unmarshaler.Unmarshal(nil) require.Error(t, err) diff --git a/receiver/awsfirehosereceiver/internal/unmarshaler/unmarshalertest/nop_metrics_unmarshaler_test.go b/receiver/awsfirehosereceiver/internal/unmarshaler/unmarshalertest/nop_metrics_unmarshaler_test.go index f48aa1ebd51a..572c39bc475c 100644 --- a/receiver/awsfirehosereceiver/internal/unmarshaler/unmarshalertest/nop_metrics_unmarshaler_test.go +++ b/receiver/awsfirehosereceiver/internal/unmarshaler/unmarshalertest/nop_metrics_unmarshaler_test.go @@ -4,7 +4,7 @@ package unmarshalertest import ( - "fmt" + "errors" "testing" "github.com/stretchr/testify/require" @@ -31,7 +31,7 @@ func TestNewWithMetrics(t *testing.T) { } func TestNewErrMetrics(t *testing.T) { - wantErr := fmt.Errorf("test error") + wantErr := errors.New("test error") unmarshaler := NewErrMetrics(wantErr) got, err := unmarshaler.Unmarshal(nil) require.Error(t, err) diff --git a/receiver/awsfirehosereceiver/receiver.go b/receiver/awsfirehosereceiver/receiver.go index 4d78eb2778d2..79cc3e42751c 100644 --- a/receiver/awsfirehosereceiver/receiver.go +++ b/receiver/awsfirehosereceiver/receiver.go @@ -12,6 +12,7 @@ import ( "io" "net" "net/http" + "strconv" "sync" "time" @@ -282,7 +283,7 @@ func (fmr *firehoseReceiver) sendResponse(w http.ResponseWriter, requestID strin } payload, _ := json.Marshal(body) w.Header().Set(headerContentType, "application/json") - w.Header().Set(headerContentLength, fmt.Sprintf("%d", len(payload))) + w.Header().Set(headerContentLength, strconv.Itoa(len(payload))) w.WriteHeader(statusCode) if _, err = w.Write(payload); err != nil { fmr.settings.Logger.Error("Failed to send response", zap.Error(err)) diff --git a/receiver/awsfirehosereceiver/receiver_test.go b/receiver/awsfirehosereceiver/receiver_test.go index e0ece7054d72..2a70846462f5 100644 --- a/receiver/awsfirehosereceiver/receiver_test.go +++ b/receiver/awsfirehosereceiver/receiver_test.go @@ -13,6 +13,7 @@ import ( "net" "net/http" "net/http/httptest" + "strconv" "testing" "time" @@ -190,7 +191,7 @@ func TestFirehoseRequest(t *testing.T) { request := httptest.NewRequest(http.MethodPost, "/", requestBody) request.Header.Set(headerContentType, "application/json") - request.Header.Set(headerContentLength, fmt.Sprintf("%d", requestBody.Len())) + request.Header.Set(headerContentLength, strconv.Itoa(requestBody.Len())) request.Header.Set(headerFirehoseRequestID, testFirehoseRequestID) request.Header.Set(headerFirehoseAccessKey, testFirehoseAccessKey) if testCase.headers != nil { diff --git a/receiver/awss3receiver/notifications_test.go b/receiver/awss3receiver/notifications_test.go index 8d3693a85936..981358776a14 100644 --- a/receiver/awss3receiver/notifications_test.go +++ b/receiver/awss3receiver/notifications_test.go @@ -5,7 +5,7 @@ package awss3receiver // import "github.com/open-telemetry/opentelemetry-collect import ( "context" - "fmt" + "errors" "testing" "time" @@ -65,7 +65,7 @@ func (h hostWithCustomCapabilityRegistry) GetExtensions() map[component.ID]compo func (m *mockCustomCapabilityRegistry) Register(_ string, _ ...opampcustommessages.CustomCapabilityRegisterOption) (handler opampcustommessages.CustomCapabilityHandler, err error) { if m.shouldFailRegister { - return nil, fmt.Errorf("register failed") + return nil, errors.New("register failed") } if m.shouldRegisterReturnNilHandler { return nil, nil @@ -80,13 +80,13 @@ func (m *mockCustomCapabilityRegistry) Message() <-chan *protobufs.CustomMessage func (m *mockCustomCapabilityRegistry) SendMessage(messageType string, message []byte) (messageSendingChannel chan struct{}, err error) { m.sendMessageCalls++ if m.unregisterCalled { - return nil, fmt.Errorf("unregister called") + return nil, errors.New("unregister called") } if m.shouldReturnPending != nil && m.shouldReturnPending() { return m.pendingChannel, types.ErrCustomMessagePending } if m.shouldFailSend { - return nil, fmt.Errorf("send failed") + return nil, errors.New("send failed") } m.sentMessages = append(m.sentMessages, customMessage{messageType: messageType, message: message}) return nil, nil diff --git a/receiver/awss3receiver/s3reader_test.go b/receiver/awss3receiver/s3reader_test.go index 7dfe9ba4c92f..dbbe4c23b397 100644 --- a/receiver/awss3receiver/s3reader_test.go +++ b/receiver/awss3receiver/s3reader_test.go @@ -126,7 +126,7 @@ func (m *mockListObjectsV2Pager) NextPage(_ context.Context, _ ...func(*s3.Optio } if m.PageNum >= len(m.Pages) { - return nil, fmt.Errorf("no more pages") + return nil, errors.New("no more pages") } output = m.Pages[m.PageNum] m.PageNum++ diff --git a/receiver/awsxrayreceiver/internal/translator/translator_test.go b/receiver/awsxrayreceiver/internal/translator/translator_test.go index 68231cd57d8e..658bece18c0f 100644 --- a/receiver/awsxrayreceiver/internal/translator/translator_test.go +++ b/receiver/awsxrayreceiver/internal/translator/translator_test.go @@ -677,8 +677,7 @@ func TestTranslation(t *testing.T) { actualSeg *awsxray.Segment, _ ptrace.ResourceSpans, _ ptrace.Traces, err error) { assert.EqualError(t, err, - fmt.Sprintf("unexpected namespace: %s", - *actualSeg.Subsegments[0].Subsegments[0].Namespace), + "unexpected namespace: "+*actualSeg.Subsegments[0].Subsegments[0].Namespace, testCase+": translation should've failed") }, }, @@ -845,10 +844,7 @@ func TestTranslation(t *testing.T) { actualSeg *awsxray.Segment, _ ptrace.ResourceSpans, _ ptrace.Traces, err error) { assert.EqualError(t, err, - fmt.Sprintf( - "failed to parse out the database name in the \"sql.url\" field, rawUrl: %s", - *actualSeg.SQL.URL, - ), + "failed to parse out the database name in the \"sql.url\" field, rawUrl: "+*actualSeg.SQL.URL, testCase+": translation should've failed") }, }, diff --git a/receiver/chronyreceiver/config_test.go b/receiver/chronyreceiver/config_test.go index 3459cb5019f1..d2fda85fc916 100644 --- a/receiver/chronyreceiver/config_test.go +++ b/receiver/chronyreceiver/config_test.go @@ -4,7 +4,6 @@ package chronyreceiver import ( - "fmt" "os" "path/filepath" "testing" @@ -90,7 +89,7 @@ func TestValidate(t *testing.T) { { scenario: "Valid unix path", conf: Config{ - Endpoint: fmt.Sprintf("unix://%s", t.TempDir()), + Endpoint: "unix://" + t.TempDir(), ControllerConfig: scraperhelper.ControllerConfig{ CollectionInterval: time.Minute, InitialDelay: time.Second, diff --git a/receiver/chronyreceiver/internal/chrony/client_test.go b/receiver/chronyreceiver/internal/chrony/client_test.go index dd6733b07ce8..0343866d4e11 100644 --- a/receiver/chronyreceiver/internal/chrony/client_test.go +++ b/receiver/chronyreceiver/internal/chrony/client_test.go @@ -211,7 +211,7 @@ func TestGettingTrackingData(t *testing.T) { t.Run(tc.scenario, func(t *testing.T) { t.Parallel() - client, err := New(fmt.Sprintf("unix://%s", t.TempDir()), tc.timeout, func(c *client) { + client, err := New("unix://"+t.TempDir(), tc.timeout, func(c *client) { c.dialer = func(context.Context, string, string) (net.Conn, error) { if tc.dialTime > tc.timeout { return nil, os.ErrDeadlineExceeded diff --git a/receiver/chronyreceiver/internal/chrony/util_test.go b/receiver/chronyreceiver/internal/chrony/util_test.go index 7f9641defec0..cc142bb06bb6 100644 --- a/receiver/chronyreceiver/internal/chrony/util_test.go +++ b/receiver/chronyreceiver/internal/chrony/util_test.go @@ -4,7 +4,6 @@ package chrony import ( - "fmt" "os" "testing" @@ -46,7 +45,7 @@ func TestSplitNetworkEndpoint(t *testing.T) { }, { scenario: "A valid UNIX network", - in: fmt.Sprintf("unix://%s", path), + in: "unix://" + path, network: "unixgram", endpoint: path, err: nil, diff --git a/receiver/cloudflarereceiver/logs.go b/receiver/cloudflarereceiver/logs.go index 956b38118ca4..36d72d63f4b8 100644 --- a/receiver/cloudflarereceiver/logs.go +++ b/receiver/cloudflarereceiver/logs.go @@ -241,12 +241,12 @@ func (l *logsReceiver) processLogs(now pcommon.Timestamp, logs []map[string]any) if stringV, ok := v.(string); ok { ts, err := time.Parse(time.RFC3339, stringV) if err != nil { - l.logger.Warn(fmt.Sprintf("unable to parse %s", l.cfg.TimestampField), zap.Error(err), zap.String("value", stringV)) + l.logger.Warn("unable to parse "+l.cfg.TimestampField, zap.Error(err), zap.String("value", stringV)) } else { logRecord.SetTimestamp(pcommon.NewTimestampFromTime(ts)) } } else { - l.logger.Warn(fmt.Sprintf("unable to parse %s", l.cfg.TimestampField), zap.Any("value", v)) + l.logger.Warn("unable to parse "+l.cfg.TimestampField, zap.Any("value", v)) } } diff --git a/receiver/couchdbreceiver/metrics.go b/receiver/couchdbreceiver/metrics.go index ff759f542e28..1081772f5f03 100644 --- a/receiver/couchdbreceiver/metrics.go +++ b/receiver/couchdbreceiver/metrics.go @@ -4,7 +4,7 @@ package couchdbreceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/couchdbreceiver" import ( - "fmt" + "errors" "go.opentelemetry.io/collector/pdata/pcommon" "go.opentelemetry.io/collector/receiver/scrapererror" @@ -156,12 +156,12 @@ func getValueFromBody(keys []string, body map[string]any) (any, error) { for _, key := range keys { currentBody, ok := currentValue.(map[string]any) if !ok { - return nil, fmt.Errorf("could not find key in body") + return nil, errors.New("could not find key in body") } currentValue, ok = currentBody[key] if !ok { - return nil, fmt.Errorf("could not find key in body") + return nil, errors.New("could not find key in body") } } return currentValue, nil @@ -174,12 +174,12 @@ func (c *couchdbScraper) parseInt(value any) (int64, error) { case float64: return int64(i), nil } - return 0, fmt.Errorf("could not parse value as int") + return 0, errors.New("could not parse value as int") } func (c *couchdbScraper) parseFloat(value any) (float64, error) { if f, ok := value.(float64); ok { return f, nil } - return 0, fmt.Errorf("could not parse value as float") + return 0, errors.New("could not parse value as float") } diff --git a/receiver/datadogreceiver/internal/translator/tags.go b/receiver/datadogreceiver/internal/translator/tags.go index e2cfc3da4f80..3e50f612bcd9 100644 --- a/receiver/datadogreceiver/internal/translator/tags.go +++ b/receiver/datadogreceiver/internal/translator/tags.go @@ -4,7 +4,6 @@ package translator // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/datadogreceiver/internal/translator" import ( - "fmt" "strings" "sync" @@ -70,7 +69,7 @@ func translateDatadogTagToKeyValuePair(tag string) (key string, value string) { // to only support key:value pairs. // The following is a workaround to map unnamed inputTags to key:value pairs and its subject to future // changes if OTel supports unnamed inputTags in the future or if there is a better way to do this. - key = fmt.Sprintf("unnamed_%s", tag) + key = "unnamed_" + tag val = tag } return key, val diff --git a/receiver/datadogreceiver/internal/translator/traces_translator_test.go b/receiver/datadogreceiver/internal/translator/traces_translator_test.go index c0d43fae9600..e3bba6831829 100644 --- a/receiver/datadogreceiver/internal/translator/traces_translator_test.go +++ b/receiver/datadogreceiver/internal/translator/traces_translator_test.go @@ -178,11 +178,11 @@ func agentPayloadFromTraces(traces *pb.Traces) (agentPayload pb.AgentPayload) { var tracerPayloads []*pb.TracerPayload for i := 0; i < numberOfTraces; i++ { payload := &pb.TracerPayload{ - LanguageName: fmt.Sprintf("%d", i), - LanguageVersion: fmt.Sprintf("%d", i), - ContainerID: fmt.Sprintf("%d", i), + LanguageName: strconv.Itoa(i), + LanguageVersion: strconv.Itoa(i), + ContainerID: strconv.Itoa(i), Chunks: traceChunksFromTraces(*traces), - TracerVersion: fmt.Sprintf("%d", i), + TracerVersion: strconv.Itoa(i), } tracerPayloads = append(tracerPayloads, payload) } diff --git a/receiver/datadogreceiver/receiver.go b/receiver/datadogreceiver/receiver.go index 17b2814ce007..23ba993e3578 100644 --- a/receiver/datadogreceiver/receiver.go +++ b/receiver/datadogreceiver/receiver.go @@ -423,7 +423,7 @@ func (ddr *datadogReceiver) handleIntake(w http.ResponseWriter, req *http.Reques ddr.tReceiver.EndMetricsOp(obsCtx, "datadog", *metricsCount, err) }(&metricsCount) - err = fmt.Errorf("intake endpoint not implemented") + err = errors.New("intake endpoint not implemented") http.Error(w, err.Error(), http.StatusMethodNotAllowed) ddr.params.Logger.Warn("metrics consumer errored out", zap.Error(err)) } @@ -437,7 +437,7 @@ func (ddr *datadogReceiver) handleDistributionPoints(w http.ResponseWriter, req ddr.tReceiver.EndMetricsOp(obsCtx, "datadog", *metricsCount, err) }(&metricsCount) - err = fmt.Errorf("distribution points endpoint not implemented") + err = errors.New("distribution points endpoint not implemented") http.Error(w, err.Error(), http.StatusMethodNotAllowed) ddr.params.Logger.Warn("metrics consumer errored out", zap.Error(err)) } diff --git a/receiver/dockerstatsreceiver/receiver.go b/receiver/dockerstatsreceiver/receiver.go index 1b82c04611bc..7c5bf463cad7 100644 --- a/receiver/dockerstatsreceiver/receiver.go +++ b/receiver/dockerstatsreceiver/receiver.go @@ -270,7 +270,7 @@ func (r *metricsReceiver) recordCPUMetrics(now pcommon.Timestamp, cpuStats *ctyp r.mb.RecordContainerCPULogicalCountDataPoint(now, int64(cpuStats.OnlineCPUs)) for coreNum, v := range cpuStats.CPUUsage.PercpuUsage { - r.mb.RecordContainerCPUUsagePercpuDataPoint(now, int64(v), fmt.Sprintf("cpu%s", strconv.Itoa(coreNum))) + r.mb.RecordContainerCPUUsagePercpuDataPoint(now, int64(v), "cpu"+strconv.Itoa(coreNum)) } } diff --git a/receiver/elasticsearchreceiver/client.go b/receiver/elasticsearchreceiver/client.go index d70067cb0b86..b5312a9a17c8 100644 --- a/receiver/elasticsearchreceiver/client.go +++ b/receiver/elasticsearchreceiver/client.go @@ -63,7 +63,7 @@ func newElasticsearchClient(ctx context.Context, settings component.TelemetrySet if c.Username != "" && c.Password != "" { userPass := fmt.Sprintf("%s:%s", c.Username, string(c.Password)) authb64 := base64.StdEncoding.EncodeToString([]byte(userPass)) - authHeader = fmt.Sprintf("Basic %s", authb64) + authHeader = "Basic " + authb64 } esClient := defaultElasticsearchClient{ @@ -204,7 +204,7 @@ func (c defaultElasticsearchClient) ClusterStats(ctx context.Context, nodes []st nodesSpec = "_all" } - clusterStatsPath := fmt.Sprintf("_cluster/stats/nodes/%s", nodesSpec) + clusterStatsPath := "_cluster/stats/nodes/" + nodesSpec body, err := c.doRequest(ctx, clusterStatsPath) if err != nil { diff --git a/receiver/expvarreceiver/config.go b/receiver/expvarreceiver/config.go index 0718a5aa49f1..fcd51334ea70 100644 --- a/receiver/expvarreceiver/config.go +++ b/receiver/expvarreceiver/config.go @@ -4,6 +4,7 @@ package expvarreceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/expvarreceiver" import ( + "errors" "fmt" "net/url" @@ -31,7 +32,7 @@ func (c *Config) Validate() error { return fmt.Errorf("scheme must be 'http' or 'https', but was '%s'", u.Scheme) } if u.Host == "" { - return fmt.Errorf("host not found in HTTP endpoint") + return errors.New("host not found in HTTP endpoint") } return nil } diff --git a/receiver/expvarreceiver/scraper.go b/receiver/expvarreceiver/scraper.go index 44a20dd075ca..93c7270cd7f0 100644 --- a/receiver/expvarreceiver/scraper.go +++ b/receiver/expvarreceiver/scraper.go @@ -6,6 +6,7 @@ package expvarreceiver // import "github.com/open-telemetry/opentelemetry-collec import ( "context" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -70,7 +71,7 @@ func (e *expVarScraper) scrape(ctx context.Context) (pmetric.Metrics, error) { } memStats := result.MemStats if memStats == nil { - return emptyMetrics, fmt.Errorf("unmarshalled memstats data is nil") + return emptyMetrics, errors.New("unmarshalled memstats data is nil") } now := pcommon.NewTimestampFromTime(time.Now()) diff --git a/receiver/filelogreceiver/filelog_test.go b/receiver/filelogreceiver/filelog_test.go index 80931bbe87ee..d4968df3158d 100644 --- a/receiver/filelogreceiver/filelog_test.go +++ b/receiver/filelogreceiver/filelog_test.go @@ -11,6 +11,7 @@ import ( "os" "path/filepath" "runtime" + "strconv" "sync" "sync/atomic" "testing" @@ -320,7 +321,7 @@ func rotationTestConfig(tempDir string) *FileLogConfig { }, InputConfig: func() file.Config { c := file.NewConfig() - c.Include = []string{fmt.Sprintf("%s/*", tempDir)} + c.Include = []string{tempDir + "/*"} c.StartAt = "beginning" c.PollInterval = 10 * time.Millisecond c.IncludeFileName = false @@ -383,7 +384,7 @@ func (g *fileLogGenerator) Stop() { } func (g *fileLogGenerator) Generate() []receivertest.UniqueIDAttrVal { - id := receivertest.UniqueIDAttrVal(fmt.Sprintf("%d", atomic.AddInt64(&g.sequenceNum, 1))) + id := receivertest.UniqueIDAttrVal(strconv.FormatInt(atomic.AddInt64(&g.sequenceNum, 1), 10)) logLine := fmt.Sprintf(`{"ts": "%s", "log": "log-%s", "%s": "%s"}`, time.Now().Format(time.RFC3339), id, receivertest.UniqueIDAttrName, id) _, err := g.tmpFile.WriteString(logLine + "\n") diff --git a/receiver/flinkmetricsreceiver/client.go b/receiver/flinkmetricsreceiver/client.go index 8b02cf66ca35..a2d8b51659ce 100644 --- a/receiver/flinkmetricsreceiver/client.go +++ b/receiver/flinkmetricsreceiver/client.go @@ -10,6 +10,7 @@ import ( "io" "net/http" "os" + "strconv" "strings" "go.opentelemetry.io/collector/component" @@ -313,7 +314,7 @@ func (c *flinkClient) getSubtasksMetricsByIDs(ctx context.Context, jobsResponse TaskmanagerID: getTaskmanagerID(subtask.TaskmanagerID), JobName: jobsWithIDResponse.Name, TaskName: vertex.Name, - SubtaskIndex: fmt.Sprintf("%v", subtask.Subtask), + SubtaskIndex: strconv.Itoa(subtask.Subtask), Metrics: *subtaskMetrics, }) } diff --git a/receiver/googlecloudmonitoringreceiver/receiver.go b/receiver/googlecloudmonitoringreceiver/receiver.go index 4b0d6b256e20..f852e596de65 100644 --- a/receiver/googlecloudmonitoringreceiver/receiver.go +++ b/receiver/googlecloudmonitoringreceiver/receiver.go @@ -160,7 +160,7 @@ func (mr *monitoringReceiver) initializeClient(ctx context.Context) error { return fmt.Errorf("failed to find default credentials: %w", err) } if creds == nil || creds.JSON == nil { - return fmt.Errorf("no valid credentials found") + return errors.New("no valid credentials found") } // Attempt to create the monitoring client diff --git a/receiver/googlecloudpubsubreceiver/internal/handler.go b/receiver/googlecloudpubsubreceiver/internal/handler.go index fbb466fed8cb..ea879c857d39 100644 --- a/receiver/googlecloudpubsubreceiver/internal/handler.go +++ b/receiver/googlecloudpubsubreceiver/internal/handler.go @@ -213,7 +213,7 @@ func (handler *StreamHandler) responseStream(ctx context.Context, cancel context time.Sleep(time.Second * 60) activeStreaming = false default: - handler.logger.Warn(fmt.Sprintf("response stream breaking on gRPC s %s", s.Message()), + handler.logger.Warn("response stream breaking on gRPC s "+s.Message(), zap.String("s", s.Message()), zap.Error(err)) activeStreaming = false diff --git a/receiver/googlecloudspannerreceiver/internal/metadata/metricsdatapoint.go b/receiver/googlecloudspannerreceiver/internal/metadata/metricsdatapoint.go index 26f76aec92df..591309082a49 100644 --- a/receiver/googlecloudspannerreceiver/internal/metadata/metricsdatapoint.go +++ b/receiver/googlecloudspannerreceiver/internal/metadata/metricsdatapoint.go @@ -4,8 +4,8 @@ package metadata // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/googlecloudspannerreceiver/internal/metadata" import ( - "fmt" "hash/fnv" + "strconv" "strings" "time" "unicode/utf8" @@ -126,9 +126,9 @@ func parseAndHashRowrangestartkey(key string) string { hashFunction.Reset() hashFunction.Write([]byte(subKey)) if cnt < len(keySlice)-1 { - builderHashedKey.WriteString(fmt.Sprint(hashFunction.Sum32()) + ",") + builderHashedKey.WriteString(strconv.FormatUint(uint64(hashFunction.Sum32()), 10) + ",") } else { - builderHashedKey.WriteString(fmt.Sprint(hashFunction.Sum32())) + builderHashedKey.WriteString(strconv.FormatUint(uint64(hashFunction.Sum32()), 10)) } } if plusPresent { @@ -182,5 +182,5 @@ func (mdp *MetricsDataPoint) hash() (string, error) { return "", err } - return fmt.Sprintf("%x", hashedData), nil + return strconv.FormatUint(hashedData, 16), nil } diff --git a/receiver/googlecloudspannerreceiver/internal/metadata/metricsdatapoint_test.go b/receiver/googlecloudspannerreceiver/internal/metadata/metricsdatapoint_test.go index b837b0f6e04a..6d277ff68998 100644 --- a/receiver/googlecloudspannerreceiver/internal/metadata/metricsdatapoint_test.go +++ b/receiver/googlecloudspannerreceiver/internal/metadata/metricsdatapoint_test.go @@ -4,8 +4,8 @@ package metadata import ( - "fmt" "hash/fnv" + "strconv" "testing" "time" @@ -119,10 +119,10 @@ func TestMetricsDataPoint_HideLockStatsRowrangestartkeyPII(t *testing.T) { hashFunction := fnv.New32a() hashFunction.Reset() hashFunction.Write([]byte("23")) - hashOf23 := fmt.Sprint(hashFunction.Sum32()) + hashOf23 := strconv.FormatUint(uint64(hashFunction.Sum32()), 10) hashFunction.Reset() hashFunction.Write([]byte("hello")) - hashOfHello := fmt.Sprint(hashFunction.Sum32()) + hashOfHello := strconv.FormatUint(uint64(hashFunction.Sum32()), 10) metricsDataPoint.HideLockStatsRowrangestartkeyPII() diff --git a/receiver/hostmetricsreceiver/internal/perfcounters/perfcounter_scraper_errors.go b/receiver/hostmetricsreceiver/internal/perfcounters/perfcounter_scraper_errors.go index a38c41be96ef..b2f472896657 100644 --- a/receiver/hostmetricsreceiver/internal/perfcounters/perfcounter_scraper_errors.go +++ b/receiver/hostmetricsreceiver/internal/perfcounters/perfcounter_scraper_errors.go @@ -4,7 +4,6 @@ package perfcounters // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/hostmetricsreceiver/internal/perfcounters" import ( - "fmt" "strings" ) @@ -13,7 +12,7 @@ type PerfCounterInitError struct { } func (p *PerfCounterInitError) Error() string { - return fmt.Sprintf("failed to init counters: %s", strings.Join(p.FailedObjects, "; ")) + return "failed to init counters: " + strings.Join(p.FailedObjects, "; ") } func (p *PerfCounterInitError) AddFailure(object string) { diff --git a/receiver/jaegerreceiver/config.go b/receiver/jaegerreceiver/config.go index 4ed9dda665ca..be6d3bb0cf36 100644 --- a/receiver/jaegerreceiver/config.go +++ b/receiver/jaegerreceiver/config.go @@ -4,6 +4,7 @@ package jaegerreceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/jaegerreceiver" import ( + "errors" "fmt" "net" "strconv" @@ -81,7 +82,7 @@ func (cfg *Config) Validate() error { cfg.ThriftHTTP == nil && cfg.ThriftBinary == nil && cfg.ThriftCompact == nil { - return fmt.Errorf("must specify at least one protocol when using the Jaeger receiver") + return errors.New("must specify at least one protocol when using the Jaeger receiver") } if cfg.GRPC != nil { @@ -110,7 +111,7 @@ func (cfg *Config) Validate() error { if cfg.RemoteSampling != nil { if disableJaegerReceiverRemoteSampling.IsEnabled() { - return fmt.Errorf("remote sampling config detected in the Jaeger receiver; use the `jaegerremotesampling` extension instead") + return errors.New("remote sampling config detected in the Jaeger receiver; use the `jaegerremotesampling` extension instead") } } @@ -120,7 +121,7 @@ func (cfg *Config) Validate() error { // Unmarshal a config.Parser into the config struct. func (cfg *Config) Unmarshal(componentParser *confmap.Conf) error { if componentParser == nil || len(componentParser.AllKeys()) == 0 { - return fmt.Errorf("empty config for Jaeger receiver") + return errors.New("empty config for Jaeger receiver") } // UnmarshalExact will not set struct properties to nil even if no key is provided, @@ -163,7 +164,7 @@ func checkPortFromEndpoint(endpoint string) error { return fmt.Errorf("endpoint port is not a number: %w", err) } if port < 1 || port > 65535 { - return fmt.Errorf("port number must be between 1 and 65535") + return errors.New("port number must be between 1 and 65535") } return nil } diff --git a/receiver/jaegerreceiver/trace_receiver.go b/receiver/jaegerreceiver/trace_receiver.go index 1eb1159639d3..e68101c13c4c 100644 --- a/receiver/jaegerreceiver/trace_receiver.go +++ b/receiver/jaegerreceiver/trace_receiver.go @@ -173,7 +173,7 @@ var _ agent.Agent = (*agentHandler)(nil) var _ api_v2.CollectorServiceServer = (*jReceiver)(nil) var _ configmanager.ClientConfigManager = (*notImplementedConfigManager)(nil) -var errNotImplemented = fmt.Errorf("not implemented") +var errNotImplemented = errors.New("not implemented") type notImplementedConfigManager struct{} diff --git a/receiver/jmxreceiver/config.go b/receiver/jmxreceiver/config.go index b31534dae3bf..e38712125208 100644 --- a/receiver/jmxreceiver/config.go +++ b/receiver/jmxreceiver/config.go @@ -101,7 +101,7 @@ func (c *Config) parseProperties(logger *zap.Logger) []string { logLevel = getZapLoggerLevelEquivalent(logger) } - parsed = append(parsed, fmt.Sprintf("-Dorg.slf4j.simpleLogger.defaultLogLevel=%s", logLevel)) + parsed = append(parsed, "-Dorg.slf4j.simpleLogger.defaultLogLevel="+logLevel) // Sorted for testing and reproducibility sort.Strings(parsed) return parsed diff --git a/receiver/jmxreceiver/internal/subprocess/subprocess.go b/receiver/jmxreceiver/internal/subprocess/subprocess.go index e1a8dfc48a04..e50656eecfb3 100644 --- a/receiver/jmxreceiver/internal/subprocess/subprocess.go +++ b/receiver/jmxreceiver/internal/subprocess/subprocess.go @@ -6,6 +6,7 @@ package subprocess // import "github.com/open-telemetry/opentelemetry-collector- import ( "bufio" "context" + "errors" "fmt" "io" "os" @@ -123,7 +124,7 @@ func (subprocess *Subprocess) Start(ctx context.Context) error { // Shutdown is invoked during service shutdown. func (subprocess *Subprocess) Shutdown(ctx context.Context) error { if subprocess.cancel == nil { - return fmt.Errorf("no subprocess.cancel(). Has it been started properly?") + return errors.New("no subprocess.cancel(). Has it been started properly?") } timeout := defaultShutdownTimeout diff --git a/receiver/jmxreceiver/receiver.go b/receiver/jmxreceiver/receiver.go index 61274cc4254a..df62ffea1f27 100644 --- a/receiver/jmxreceiver/receiver.go +++ b/receiver/jmxreceiver/receiver.go @@ -155,7 +155,7 @@ func (jmx *jmxMetricReceiver) buildOTLPReceiver() (receiver.Metrics, error) { } defer listener.Close() addr := listener.Addr().(*net.TCPAddr) - port = fmt.Sprintf("%d", addr.Port) + port = strconv.Itoa(addr.Port) endpoint = fmt.Sprintf("%s:%s", host, port) jmx.config.OTLPExporterConfig.Endpoint = endpoint } @@ -194,7 +194,7 @@ func (jmx *jmxMetricReceiver) buildJMXMetricGathererConfig() (string, error) { endpoint := jmx.config.OTLPExporterConfig.Endpoint if !strings.HasPrefix(endpoint, "http") { - endpoint = fmt.Sprintf("http://%s", endpoint) + endpoint = "http://" + endpoint } config["otel.metrics.exporter"] = "otlp" diff --git a/receiver/k8sclusterreceiver/internal/metadata/metadata.go b/receiver/k8sclusterreceiver/internal/metadata/metadata.go index a630239cb754..5ea50a953f7b 100644 --- a/receiver/k8sclusterreceiver/internal/metadata/metadata.go +++ b/receiver/k8sclusterreceiver/internal/metadata/metadata.go @@ -54,8 +54,7 @@ func GetGenericMetadata(om *v1.ObjectMeta, resourceType string) *KubernetesMetad metadata[constants.K8sKeyWorkLoadKind] = resourceType metadata[constants.K8sKeyWorkLoadName] = om.Name - metadata[fmt.Sprintf("%s.creation_timestamp", - rType)] = om.GetCreationTimestamp().Format(time.RFC3339) + metadata[rType+".creation_timestamp"] = om.GetCreationTimestamp().Format(time.RFC3339) for _, or := range om.OwnerReferences { kind := strings.ToLower(or.Kind) @@ -80,7 +79,7 @@ func GetOTelNameFromKind(kind string) string { } func getOTelEntityTypeFromKind(kind string) string { - return fmt.Sprintf("k8s.%s", kind) + return "k8s." + kind } // mergeKubernetesMetadataMaps merges maps of string (resource id) to diff --git a/receiver/k8sclusterreceiver/internal/node/nodes.go b/receiver/k8sclusterreceiver/internal/node/nodes.go index f762b7e14ae3..9426718981d9 100644 --- a/receiver/k8sclusterreceiver/internal/node/nodes.go +++ b/receiver/k8sclusterreceiver/internal/node/nodes.go @@ -172,7 +172,7 @@ func getContainerRuntimeInfo(rawInfo string) (runtime string, version string) { return "", "" } func getNodeConditionMetric(nodeConditionTypeValue string) string { - return fmt.Sprintf("k8s.node.condition_%s", strcase.ToSnake(nodeConditionTypeValue)) + return "k8s.node.condition_" + strcase.ToSnake(nodeConditionTypeValue) } func getNodeAllocatableUnit(res corev1.ResourceName) string { @@ -198,5 +198,5 @@ func setNodeAllocatableValue(dp pmetric.NumberDataPoint, res corev1.ResourceName } func getNodeAllocatableMetric(nodeAllocatableTypeValue string) string { - return fmt.Sprintf("k8s.node.allocatable_%s", strcase.ToSnake(nodeAllocatableTypeValue)) + return "k8s.node.allocatable_" + strcase.ToSnake(nodeAllocatableTypeValue) } diff --git a/receiver/k8sclusterreceiver/receiver.go b/receiver/k8sclusterreceiver/receiver.go index ae9c5f75ca8b..10e90b16fc5f 100644 --- a/receiver/k8sclusterreceiver/receiver.go +++ b/receiver/k8sclusterreceiver/receiver.go @@ -6,7 +6,6 @@ package k8sclusterreceiver // import "github.com/open-telemetry/opentelemetry-co import ( "context" "errors" - "fmt" "time" "go.opentelemetry.io/collector/component" @@ -52,7 +51,7 @@ func (kr *kubernetesReceiver) Start(ctx context.Context, host component.Host) er ge, ok := host.(getExporters) if !ok { - return fmt.Errorf("unable to get exporters") + return errors.New("unable to get exporters") } exporters := ge.GetExporters() diff --git a/receiver/k8sobjectsreceiver/config.go b/receiver/k8sobjectsreceiver/config.go index 62c303748e35..fc4d9bc487e3 100644 --- a/receiver/k8sobjectsreceiver/config.go +++ b/receiver/k8sobjectsreceiver/config.go @@ -4,6 +4,7 @@ package k8sobjectsreceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/k8sobjectsreceiver" import ( + "errors" "fmt" "strings" "time" @@ -90,7 +91,7 @@ func (c *Config) Validate() error { } if object.Mode == PullMode && len(object.ExcludeWatchType) != 0 { - return fmt.Errorf("the Exclude config can only be used with watch mode") + return errors.New("the Exclude config can only be used with watch mode") } object.gvr = gvr diff --git a/receiver/k8sobjectsreceiver/receiver.go b/receiver/k8sobjectsreceiver/receiver.go index d69df14a19e6..c1e82babd5dc 100644 --- a/receiver/k8sobjectsreceiver/receiver.go +++ b/receiver/k8sobjectsreceiver/receiver.go @@ -5,6 +5,7 @@ package k8sobjectsreceiver // import "github.com/open-telemetry/opentelemetry-co import ( "context" + "errors" "fmt" "net/http" "sync" @@ -252,7 +253,7 @@ func getResourceVersion(ctx context.Context, config *K8sObjectsConfig, resource return "", fmt.Errorf("could not perform initial list for watch on %v, %w", config.gvr.String(), err) } if objects == nil { - return "", fmt.Errorf("nil objects returned, this is an error in the k8sobjectsreceiver") + return "", errors.New("nil objects returned, this is an error in the k8sobjectsreceiver") } resourceVersion = objects.GetResourceVersion() diff --git a/receiver/kafkametricsreceiver/broker_scraper_test.go b/receiver/kafkametricsreceiver/broker_scraper_test.go index 9616ffc5f7ce..a9d3a981d4ff 100644 --- a/receiver/kafkametricsreceiver/broker_scraper_test.go +++ b/receiver/kafkametricsreceiver/broker_scraper_test.go @@ -5,7 +5,7 @@ package kafkametricsreceiver import ( "context" - "fmt" + "errors" "testing" "github.com/IBM/sarama" @@ -66,7 +66,7 @@ func TestBrokerScraperStart(t *testing.T) { func TestBrokerScraper_scrape_handles_client_error(t *testing.T) { newSaramaClient = func([]string, *sarama.Config) (sarama.Client, error) { - return nil, fmt.Errorf("new client failed") + return nil, errors.New("new client failed") } sc := sarama.NewConfig() bs, err := createBrokerScraper(context.Background(), Config{}, sc, receivertest.NewNopSettings()) @@ -78,7 +78,7 @@ func TestBrokerScraper_scrape_handles_client_error(t *testing.T) { func TestBrokerScraper_shutdown_handles_nil_client(t *testing.T) { newSaramaClient = func([]string, *sarama.Config) (sarama.Client, error) { - return nil, fmt.Errorf("new client failed") + return nil, errors.New("new client failed") } sc := sarama.NewConfig() bs, err := createBrokerScraper(context.Background(), Config{}, sc, receivertest.NewNopSettings()) diff --git a/receiver/kafkametricsreceiver/consumer_scraper_test.go b/receiver/kafkametricsreceiver/consumer_scraper_test.go index 3ae3f01183e5..360fd5afc006 100644 --- a/receiver/kafkametricsreceiver/consumer_scraper_test.go +++ b/receiver/kafkametricsreceiver/consumer_scraper_test.go @@ -5,7 +5,7 @@ package kafkametricsreceiver import ( "context" - "fmt" + "errors" "regexp" "testing" @@ -53,7 +53,7 @@ func TestConsumerScraper_createConsumerScraper(t *testing.T) { func TestConsumerScraper_scrape_handles_client_error(t *testing.T) { newSaramaClient = func([]string, *sarama.Config) (sarama.Client, error) { - return nil, fmt.Errorf("new client failed") + return nil, errors.New("new client failed") } sc := sarama.NewConfig() cs, err := createConsumerScraper(context.Background(), Config{}, sc, receivertest.NewNopSettings()) @@ -65,7 +65,7 @@ func TestConsumerScraper_scrape_handles_client_error(t *testing.T) { func TestConsumerScraper_scrape_handles_nil_client(t *testing.T) { newSaramaClient = func([]string, *sarama.Config) (sarama.Client, error) { - return nil, fmt.Errorf("new client failed") + return nil, errors.New("new client failed") } sc := sarama.NewConfig() cs, err := createConsumerScraper(context.Background(), Config{}, sc, receivertest.NewNopSettings()) @@ -83,7 +83,7 @@ func TestConsumerScraper_scrape_handles_clusterAdmin_error(t *testing.T) { return client, nil } newClusterAdmin = func([]string, *sarama.Config) (sarama.ClusterAdmin, error) { - return nil, fmt.Errorf("new cluster admin failed") + return nil, errors.New("new cluster admin failed") } sc := sarama.NewConfig() cs, err := createConsumerScraper(context.Background(), Config{}, sc, receivertest.NewNopSettings()) diff --git a/receiver/kafkametricsreceiver/receiver_test.go b/receiver/kafkametricsreceiver/receiver_test.go index 455cc797ae04..5e37ccf39c83 100644 --- a/receiver/kafkametricsreceiver/receiver_test.go +++ b/receiver/kafkametricsreceiver/receiver_test.go @@ -5,7 +5,7 @@ package kafkametricsreceiver import ( "context" - "fmt" + "errors" "testing" "github.com/IBM/sarama" @@ -37,7 +37,7 @@ func TestNewReceiver_invalid_scraper_error(t *testing.T) { allScrapers["brokers"] = mockScraper r, err := newMetricsReceiver(context.Background(), *c, receivertest.NewNopSettings(), nil) assert.Nil(t, r) - expectedError := fmt.Errorf("no scraper found for key: cpu") + expectedError := errors.New("no scraper found for key: cpu") if assert.Error(t, err) { assert.Equal(t, expectedError, err) } @@ -75,7 +75,7 @@ func TestNewReceiver_handles_scraper_error(t *testing.T) { c := createDefaultConfig().(*Config) c.Scrapers = []string{"brokers"} mockScraper := func(context.Context, Config, *sarama.Config, receiver.Settings) (scraperhelper.Scraper, error) { - return nil, fmt.Errorf("fail") + return nil, errors.New("fail") } allScrapers["brokers"] = mockScraper r, err := newMetricsReceiver(context.Background(), *c, receivertest.NewNopSettings(), consumertest.NewNop()) diff --git a/receiver/kafkametricsreceiver/scraper_test_helper.go b/receiver/kafkametricsreceiver/scraper_test_helper.go index b3867ea4b17a..4c7cabf4ae6d 100644 --- a/receiver/kafkametricsreceiver/scraper_test_helper.go +++ b/receiver/kafkametricsreceiver/scraper_test_helper.go @@ -4,7 +4,7 @@ package kafkametricsreceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/kafkametricsreceiver" import ( - "fmt" + "errors" "strconv" "github.com/IBM/sarama" @@ -74,35 +74,35 @@ func (s *mockSaramaClient) Topics() ([]string, error) { if s.topics != nil { return s.topics, nil } - return nil, fmt.Errorf("mock topic error") + return nil, errors.New("mock topic error") } func (s *mockSaramaClient) Partitions(string) ([]int32, error) { if s.partitions != nil { return s.partitions, nil } - return nil, fmt.Errorf("mock partition error") + return nil, errors.New("mock partition error") } func (s *mockSaramaClient) GetOffset(string, int32, int64) (int64, error) { if s.offset != -1 { return s.offset, nil } - return s.offset, fmt.Errorf("mock offset error") + return s.offset, errors.New("mock offset error") } func (s *mockSaramaClient) Replicas(string, int32) ([]int32, error) { if s.replicas != nil { return s.replicas, nil } - return nil, fmt.Errorf("mock replicas error") + return nil, errors.New("mock replicas error") } func (s *mockSaramaClient) InSyncReplicas(string, int32) ([]int32, error) { if s.inSyncReplicas != nil { return s.inSyncReplicas, nil } - return nil, fmt.Errorf("mock in sync replicas error") + return nil, errors.New("mock in sync replicas error") } func newMockClient() *mockSaramaClient { @@ -134,28 +134,28 @@ type mockClusterAdmin struct { func (s *mockClusterAdmin) ListTopics() (map[string]sarama.TopicDetail, error) { if s.topics == nil { - return nil, fmt.Errorf("error getting topics") + return nil, errors.New("error getting topics") } return s.topics, nil } func (s *mockClusterAdmin) ListConsumerGroups() (map[string]string, error) { if s.consumerGroups == nil { - return nil, fmt.Errorf("error getting consumer groups") + return nil, errors.New("error getting consumer groups") } return s.consumerGroups, nil } func (s *mockClusterAdmin) DescribeConsumerGroups([]string) ([]*sarama.GroupDescription, error) { if s.consumerGroupDescriptions == nil { - return nil, fmt.Errorf("error describing consumer groups") + return nil, errors.New("error describing consumer groups") } return s.consumerGroupDescriptions, nil } func (s *mockClusterAdmin) ListConsumerGroupOffsets(string, map[string][]int32) (*sarama.OffsetFetchResponse, error) { if s.consumerGroupOffsets == nil { - return nil, fmt.Errorf("mock consumer group offset error") + return nil, errors.New("mock consumer group offset error") } return s.consumerGroupOffsets, nil } @@ -166,7 +166,7 @@ func (s *mockClusterAdmin) DescribeConfig(cr sarama.ConfigResource) ([]sarama.Co return s.brokerConfigs, nil } if s.topics[topicName].ConfigEntries == nil { - return nil, fmt.Errorf("no config entries found for topic") + return nil, errors.New("no config entries found for topic") } configEntry := make([]sarama.ConfigEntry, 1) for name, entry := range s.topics[topicName].ConfigEntries { diff --git a/receiver/kafkametricsreceiver/topic_scraper_test.go b/receiver/kafkametricsreceiver/topic_scraper_test.go index a32127a57205..62920485251e 100644 --- a/receiver/kafkametricsreceiver/topic_scraper_test.go +++ b/receiver/kafkametricsreceiver/topic_scraper_test.go @@ -5,7 +5,7 @@ package kafkametricsreceiver import ( "context" - "fmt" + "errors" "regexp" "testing" @@ -56,7 +56,7 @@ func TestTopicScraper_createsScraper(t *testing.T) { func TestTopicScraper_ScrapeHandlesError(t *testing.T) { newSaramaClient = func([]string, *sarama.Config) (sarama.Client, error) { - return nil, fmt.Errorf("no scraper here") + return nil, errors.New("no scraper here") } sc := sarama.NewConfig() ms, err := createTopicsScraper(context.Background(), Config{}, sc, receivertest.NewNopSettings()) @@ -68,7 +68,7 @@ func TestTopicScraper_ScrapeHandlesError(t *testing.T) { func TestTopicScraper_ShutdownHandlesNilClient(t *testing.T) { newSaramaClient = func([]string, *sarama.Config) (sarama.Client, error) { - return nil, fmt.Errorf("no scraper here") + return nil, errors.New("no scraper here") } sc := sarama.NewConfig() ms, err := createTopicsScraper(context.Background(), Config{}, sc, receivertest.NewNopSettings()) diff --git a/receiver/kafkareceiver/factory.go b/receiver/kafkareceiver/factory.go index a7749d45809a..be413ec507c5 100644 --- a/receiver/kafkareceiver/factory.go +++ b/receiver/kafkareceiver/factory.go @@ -5,7 +5,7 @@ package kafkareceiver // import "github.com/open-telemetry/opentelemetry-collect import ( "context" - "fmt" + "errors" "strings" "time" @@ -49,7 +49,7 @@ const ( defaultMaxFetchSize = int32(0) ) -var errUnrecognizedEncoding = fmt.Errorf("unrecognized encoding") +var errUnrecognizedEncoding = errors.New("unrecognized encoding") // FactoryOption applies changes to kafkaExporterFactory. type FactoryOption func(factory *kafkaReceiverFactory) diff --git a/receiver/kafkareceiver/header_extraction.go b/receiver/kafkareceiver/header_extraction.go index 265c84fb33db..efae723c2011 100644 --- a/receiver/kafkareceiver/header_extraction.go +++ b/receiver/kafkareceiver/header_extraction.go @@ -4,8 +4,6 @@ package kafkareceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/kafkareceiver" import ( - "fmt" - "github.com/IBM/sarama" "go.opentelemetry.io/collector/pdata/plog" "go.opentelemetry.io/collector/pdata/pmetric" @@ -14,7 +12,7 @@ import ( ) func getAttribute(key string) string { - return fmt.Sprintf("kafka.header.%s", key) + return "kafka.header." + key } type HeaderExtractor interface { diff --git a/receiver/kafkareceiver/kafka_receiver.go b/receiver/kafkareceiver/kafka_receiver.go index 48ea87559a56..497d761c8060 100644 --- a/receiver/kafkareceiver/kafka_receiver.go +++ b/receiver/kafkareceiver/kafka_receiver.go @@ -5,6 +5,7 @@ package kafkareceiver // import "github.com/open-telemetry/opentelemetry-collect import ( "context" + "errors" "fmt" "strconv" "sync" @@ -32,7 +33,7 @@ const ( attrPartition = "partition" ) -var errInvalidInitialOffset = fmt.Errorf("invalid initial offset") +var errInvalidInitialOffset = errors.New("invalid initial offset") // kafkaTracesConsumer uses sarama to consume and handle messages from kafka. type kafkaTracesConsumer struct { diff --git a/receiver/mongodbatlasreceiver/internal/mongodb_atlas_client.go b/receiver/mongodbatlasreceiver/internal/mongodb_atlas_client.go index 3f1e1bbcab2d..b3ccb9a3b737 100644 --- a/receiver/mongodbatlasreceiver/internal/mongodb_atlas_client.go +++ b/receiver/mongodbatlasreceiver/internal/mongodb_atlas_client.go @@ -6,6 +6,7 @@ package internal // import "github.com/open-telemetry/opentelemetry-collector-co import ( "bytes" "context" + "errors" "fmt" "net/http" "strconv" @@ -70,7 +71,7 @@ func (rt *clientRoundTripper) Shutdown() error { func (rt *clientRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) { if rt.isStopped() { - return nil, fmt.Errorf("request cancelled due to shutdown") + return nil, errors.New("request cancelled due to shutdown") } resp, err := rt.originalTransport.RoundTrip(r) @@ -100,9 +101,9 @@ func (rt *clientRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) zap.Duration("delay", delay)) select { case <-r.Context().Done(): - return resp, fmt.Errorf("request was cancelled or timed out") + return resp, errors.New("request was cancelled or timed out") case <-rt.shutdownChan: - return resp, fmt.Errorf("request is cancelled due to server shutdown") + return resp, errors.New("request is cancelled due to server shutdown") case <-time.After(delay): } @@ -720,9 +721,9 @@ type GetAccessLogsOptions struct { func (s *MongoDBAtlasClient) GetAccessLogs(ctx context.Context, groupID string, clusterName string, opts *GetAccessLogsOptions) (ret []*mongodbatlas.AccessLogs, err error) { options := mongodbatlas.AccessLogOptions{ // Earliest Timestamp in epoch milliseconds from when Atlas should access log results - Start: fmt.Sprintf("%d", opts.MinDate.UTC().UnixMilli()), + Start: strconv.FormatInt(opts.MinDate.UTC().UnixMilli(), 10), // Latest Timestamp in epoch milliseconds from when Atlas should access log results - End: fmt.Sprintf("%d", opts.MaxDate.UTC().UnixMilli()), + End: strconv.FormatInt(opts.MaxDate.UTC().UnixMilli(), 10), // If true, only return successful access attempts; if false, only return failed access attempts // If nil, return both successful and failed access attempts AuthResult: opts.AuthResult, diff --git a/receiver/mongodbreceiver/config.go b/receiver/mongodbreceiver/config.go index 62cace947979..17539c93d980 100644 --- a/receiver/mongodbreceiver/config.go +++ b/receiver/mongodbreceiver/config.go @@ -61,7 +61,7 @@ func (c *Config) Validate() error { func (c *Config) ClientOptions() *options.ClientOptions { clientOptions := options.Client() - connString := fmt.Sprintf("mongodb://%s", strings.Join(c.hostlist(), ",")) + connString := "mongodb://" + strings.Join(c.hostlist(), ",") clientOptions.ApplyURI(connString) if c.Timeout > 0 { diff --git a/receiver/otelarrowreceiver/internal/arrow/arrow.go b/receiver/otelarrowreceiver/internal/arrow/arrow.go index 50653b2e9a3a..21d3a421bcf7 100644 --- a/receiver/otelarrowreceiver/internal/arrow/arrow.go +++ b/receiver/otelarrowreceiver/internal/arrow/arrow.go @@ -6,7 +6,6 @@ package arrow // import "github.com/open-telemetry/opentelemetry-collector-contr import ( "context" "errors" - "fmt" "io" "runtime" "strings" @@ -50,10 +49,10 @@ const ( ) var ( - ErrNoMetricsConsumer = fmt.Errorf("no metrics consumer") - ErrNoLogsConsumer = fmt.Errorf("no logs consumer") - ErrNoTracesConsumer = fmt.Errorf("no traces consumer") - ErrUnrecognizedPayload = consumererror.NewPermanent(fmt.Errorf("unrecognized OTel-Arrow payload")) + ErrNoMetricsConsumer = errors.New("no metrics consumer") + ErrNoLogsConsumer = errors.New("no logs consumer") + ErrNoTracesConsumer = errors.New("no traces consumer") + ErrUnrecognizedPayload = consumererror.NewPermanent(errors.New("unrecognized OTel-Arrow payload")) ) type Consumers interface { diff --git a/receiver/otelarrowreceiver/internal/arrow/arrow_test.go b/receiver/otelarrowreceiver/internal/arrow/arrow_test.go index ec35cb2ef992..ea011caa82d7 100644 --- a/receiver/otelarrowreceiver/internal/arrow/arrow_test.go +++ b/receiver/otelarrowreceiver/internal/arrow/arrow_test.go @@ -7,6 +7,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "strings" @@ -340,9 +341,9 @@ func (ctc *commonTestCase) newErrorConsumer() arrowRecord.ConsumerAPI { mock := arrowRecordMock.NewMockConsumerAPI(ctc.ctrl) mock.EXPECT().Close().Times(1).Return(nil) - mock.EXPECT().TracesFrom(gomock.Any()).AnyTimes().Return(nil, fmt.Errorf("test invalid error")) - mock.EXPECT().MetricsFrom(gomock.Any()).AnyTimes().Return(nil, fmt.Errorf("test invalid error")) - mock.EXPECT().LogsFrom(gomock.Any()).AnyTimes().Return(nil, fmt.Errorf("test invalid error")) + mock.EXPECT().TracesFrom(gomock.Any()).AnyTimes().Return(nil, errors.New("test invalid error")) + mock.EXPECT().MetricsFrom(gomock.Any()).AnyTimes().Return(nil, errors.New("test invalid error")) + mock.EXPECT().LogsFrom(gomock.Any()).AnyTimes().Return(nil, errors.New("test invalid error")) return mock } @@ -549,7 +550,7 @@ func TestReceiverRecvError(t *testing.T) { ctc.start(ctc.newRealConsumer, defaultBQ()) - ctc.putBatch(nil, fmt.Errorf("test recv error")) + ctc.putBatch(nil, errors.New("test recv error")) err := ctc.wait() require.ErrorContains(t, err, "test recv error") @@ -1259,7 +1260,7 @@ func testReceiverAuthHeaders(t *testing.T, includeMeta bool, dataAuth bool) { Metadata: client.NewMetadata(newmd), }), nil } - return ctx, fmt.Errorf("not authorized") + return ctx, errors.New("not authorized") }) go func() { diff --git a/receiver/otelarrowreceiver/otelarrow_test.go b/receiver/otelarrowreceiver/otelarrow_test.go index 0cb563007358..02b966711c4c 100644 --- a/receiver/otelarrowreceiver/otelarrow_test.go +++ b/receiver/otelarrowreceiver/otelarrow_test.go @@ -575,7 +575,7 @@ func TestGRPCArrowReceiver(t *testing.T) { headerBuf.Reset() err := hpd.WriteField(hpack.HeaderField{ Name: "seq", - Value: fmt.Sprint(i), + Value: strconv.Itoa(i), }) require.NoError(t, err) err = hpd.WriteField(hpack.HeaderField{ @@ -584,7 +584,7 @@ func TestGRPCArrowReceiver(t *testing.T) { }) require.NoError(t, err) expectMDs = append(expectMDs, metadata.MD{ - "seq": []string{fmt.Sprint(i)}, + "seq": []string{strconv.Itoa(i)}, "test": []string{"value"}, }) @@ -668,7 +668,7 @@ func TestGRPCArrowReceiverAuth(t *testing.T) { map[component.ID]component.Component{ authID: newTestAuthExtension(t, func(ctx context.Context, _ map[string][]string) (context.Context, error) { if ctx.Value(inStreamCtx{}) != nil { - return ctx, fmt.Errorf(errorString) + return ctx, errors.New(errorString) } return context.WithValue(ctx, inStreamCtx{}, t), nil }), @@ -760,7 +760,7 @@ func TestConcurrentArrowReceiver(t *testing.T) { headerBuf.Reset() err := hpd.WriteField(hpack.HeaderField{ Name: "seq", - Value: fmt.Sprint(i), + Value: strconv.Itoa(i), }) assert.NoError(t, err) diff --git a/receiver/podmanreceiver/libpod_client.go b/receiver/podmanreceiver/libpod_client.go index 0e65155f2042..cb084fc67b71 100644 --- a/receiver/podmanreceiver/libpod_client.go +++ b/receiver/podmanreceiver/libpod_client.go @@ -18,7 +18,7 @@ import ( ) var ( - errNoStatsFound = fmt.Errorf("No stats found") + errNoStatsFound = errors.New("No stats found") ) type libpodClient struct { diff --git a/receiver/podmanreceiver/libpod_client_test.go b/receiver/podmanreceiver/libpod_client_test.go index 80d50ffd265f..eb23a85825b7 100644 --- a/receiver/podmanreceiver/libpod_client_test.go +++ b/receiver/podmanreceiver/libpod_client_test.go @@ -8,7 +8,6 @@ package podmanreceiver import ( "context" "errors" - "fmt" "io" "net" "net/http" @@ -60,7 +59,7 @@ func TestStats(t *testing.T) { defer srv.Close() config := &Config{ - Endpoint: fmt.Sprintf("unix://%s", addr), + Endpoint: "unix://" + addr, } cli, err := newLibpodClient(zap.NewNop(), config) @@ -116,7 +115,7 @@ func TestStatsError(t *testing.T) { defer srv.Close() config := &Config{ - Endpoint: fmt.Sprintf("unix://%s", addr), + Endpoint: "unix://" + addr, } cli, err := newLibpodClient(zap.NewNop(), config) @@ -150,7 +149,7 @@ func TestList(t *testing.T) { defer srv.Close() config := &Config{ - Endpoint: fmt.Sprintf("unix://%s", addr), + Endpoint: "unix://" + addr, } cli, err := newLibpodClient(zap.NewNop(), config) @@ -221,7 +220,7 @@ func TestEvents(t *testing.T) { defer srv.Close() config := &Config{ - Endpoint: fmt.Sprintf("unix://%s", addr), + Endpoint: "unix://" + addr, } cli, err := newLibpodClient(zap.NewNop(), config) diff --git a/receiver/podmanreceiver/podman_test.go b/receiver/podmanreceiver/podman_test.go index 3cb648587ef8..5225b940a9cc 100644 --- a/receiver/podmanreceiver/podman_test.go +++ b/receiver/podmanreceiver/podman_test.go @@ -7,7 +7,6 @@ package podmanreceiver import ( "context" - "fmt" "net/http" "net/http/httptest" "net/url" @@ -69,7 +68,7 @@ func TestWatchingTimeouts(t *testing.T) { defer os.Remove(addr) config := &Config{ - Endpoint: fmt.Sprintf("unix://%s", addr), + Endpoint: "unix://" + addr, ControllerConfig: scraperhelper.ControllerConfig{ Timeout: 50 * time.Millisecond, }, @@ -121,7 +120,7 @@ func TestEventLoopHandlesError(t *testing.T) { observed, logs := observer.New(zapcore.WarnLevel) config := &Config{ - Endpoint: fmt.Sprintf("unix://%s", addr), + Endpoint: "unix://" + addr, ControllerConfig: scraperhelper.ControllerConfig{ Timeout: 50 * time.Millisecond, }, diff --git a/receiver/postgresqlreceiver/client.go b/receiver/postgresqlreceiver/client.go index fde63bd0ba56..056167eea49c 100644 --- a/receiver/postgresqlreceiver/client.go +++ b/receiver/postgresqlreceiver/client.go @@ -116,7 +116,7 @@ func (c postgreSQLConfig) ConnectionString() (string, error) { if c.address.Transport == confignet.TransportTypeUnix { // lib/pg expects a unix socket host to start with a "/" and appends the appropriate .s.PGSQL.port internally - host = fmt.Sprintf("/%s", host) + host = "/" + host } return fmt.Sprintf("port=%s host=%s user=%s password=%s dbname=%s %s", port, host, c.username, c.password, database, sslConnectionString(c.tls)), nil diff --git a/receiver/postgresqlreceiver/scraper_test.go b/receiver/postgresqlreceiver/scraper_test.go index e660e892d869..b1c967b32aab 100644 --- a/receiver/postgresqlreceiver/scraper_test.go +++ b/receiver/postgresqlreceiver/scraper_test.go @@ -5,6 +5,7 @@ package postgresqlreceiver import ( "context" + "errors" "fmt" "path/filepath" "testing" @@ -453,7 +454,7 @@ func (m *mockClient) initMocks(database string, schema string, databases []strin lockType: "relation", locks: 5600, }, - }, fmt.Errorf("some error")) + }, errors.New("some error")) m.On("getReplicationStats", mock.Anything).Return([]replicationStats{ { clientAddr: "unix", @@ -542,8 +543,8 @@ func (m *mockClient) initMocks(database string, schema string, databases []strin m.On("getDatabaseTableMetrics", mock.Anything, database).Return(tableMetrics, nil) m.On("getBlocksReadByTable", mock.Anything, database).Return(blocksMetrics, nil) - index1 := fmt.Sprintf("%s_test1_pkey", database) - index2 := fmt.Sprintf("%s_test2_pkey", database) + index1 := database + "_test1_pkey" + index2 := database + "_test2_pkey" indexStats := map[indexIdentifer]indexStat{ indexKey(database, schema, table1, index1): { database: database, diff --git a/receiver/prometheusreceiver/metrics_receiver.go b/receiver/prometheusreceiver/metrics_receiver.go index 90613149b14b..239a6172c466 100644 --- a/receiver/prometheusreceiver/metrics_receiver.go +++ b/receiver/prometheusreceiver/metrics_receiver.go @@ -111,7 +111,7 @@ func (r *pReceiver) initPrometheusComponents(ctx context.Context, logger log.Log if r.discoveryManager == nil { // NewManager can sometimes return nil if it encountered an error, but // the error message is logged separately. - return fmt.Errorf("failed to create discovery manager") + return errors.New("failed to create discovery manager") } go func() { diff --git a/receiver/prometheusreceiver/metrics_receiver_scrape_config_files_test.go b/receiver/prometheusreceiver/metrics_receiver_scrape_config_files_test.go index 67fa4e4105b0..94329dde22f3 100644 --- a/receiver/prometheusreceiver/metrics_receiver_scrape_config_files_test.go +++ b/receiver/prometheusreceiver/metrics_receiver_scrape_config_files_test.go @@ -4,7 +4,6 @@ package prometheusreceiver import ( - "fmt" "os" "testing" @@ -42,8 +41,8 @@ func TestScrapeConfigFiles(t *testing.T) { marshalledScrapeConfigs, err := yaml.Marshal(cfg.PrometheusConfig.ScrapeConfigs) require.NoError(t, err) tmpDir := t.TempDir() - cfgFileName := fmt.Sprintf("%s/test-scrape-config.yaml", tmpDir) - scrapeConfigFileContent := fmt.Sprintf("scrape_configs:\n%s", string(marshalledScrapeConfigs)) + cfgFileName := tmpDir + "/test-scrape-config.yaml" + scrapeConfigFileContent := "scrape_configs:\n" + string(marshalledScrapeConfigs) err = os.WriteFile(cfgFileName, []byte(scrapeConfigFileContent), 0400) require.NoError(t, err) cfg.PrometheusConfig.ScrapeConfigs = []*config.ScrapeConfig{} diff --git a/receiver/prometheusreceiver/targetallocator/config.go b/receiver/prometheusreceiver/targetallocator/config.go index 5cd9d719574b..f0a1199f6490 100644 --- a/receiver/prometheusreceiver/targetallocator/config.go +++ b/receiver/prometheusreceiver/targetallocator/config.go @@ -5,6 +5,7 @@ package targetallocator // import "github.com/open-telemetry/opentelemetry-colle import ( "encoding/base64" + "errors" "fmt" "net/url" "os" @@ -37,7 +38,7 @@ func (cfg *Config) Validate() error { } // ensure valid collectorID without variables if cfg.CollectorID == "" || strings.Contains(cfg.CollectorID, "${") { - return fmt.Errorf("CollectorID is not a valid ID") + return errors.New("CollectorID is not a valid ID") } return nil diff --git a/receiver/prometheusreceiver/targetallocator/manager.go b/receiver/prometheusreceiver/targetallocator/manager.go index 06b3f2802d6d..cd431a3ed72d 100644 --- a/receiver/prometheusreceiver/targetallocator/manager.go +++ b/receiver/prometheusreceiver/targetallocator/manager.go @@ -182,7 +182,7 @@ func (m *Manager) applyCfg() error { } func getScrapeConfigsResponse(httpClient *http.Client, baseURL string) (map[string]*promconfig.ScrapeConfig, error) { - scrapeConfigsURL := fmt.Sprintf("%s/scrape_configs", baseURL) + scrapeConfigsURL := baseURL + "/scrape_configs" _, err := url.Parse(scrapeConfigsURL) // check if valid if err != nil { return nil, err diff --git a/receiver/receivercreator/consumer.go b/receiver/receivercreator/consumer.go index 35fdf7efe8bb..923ba41c171a 100644 --- a/receiver/receivercreator/consumer.go +++ b/receiver/receivercreator/consumer.go @@ -5,6 +5,7 @@ package receivercreator // import "github.com/open-telemetry/opentelemetry-colle import ( "context" + "errors" "fmt" "go.opentelemetry.io/collector/consumer" @@ -80,7 +81,7 @@ func (*enhancingConsumer) Capabilities() consumer.Capabilities { func (ec *enhancingConsumer) ConsumeLogs(ctx context.Context, ld plog.Logs) error { if ec.logs == nil { - return fmt.Errorf("no log consumer available") + return errors.New("no log consumer available") } rl := ld.ResourceLogs() for i := 0; i < rl.Len(); i++ { @@ -92,7 +93,7 @@ func (ec *enhancingConsumer) ConsumeLogs(ctx context.Context, ld plog.Logs) erro func (ec *enhancingConsumer) ConsumeMetrics(ctx context.Context, md pmetric.Metrics) error { if ec.metrics == nil { - return fmt.Errorf("no metric consumer available") + return errors.New("no metric consumer available") } rm := md.ResourceMetrics() for i := 0; i < rm.Len(); i++ { @@ -104,7 +105,7 @@ func (ec *enhancingConsumer) ConsumeMetrics(ctx context.Context, md pmetric.Metr func (ec *enhancingConsumer) ConsumeTraces(ctx context.Context, td ptrace.Traces) error { if ec.traces == nil { - return fmt.Errorf("no trace consumer available") + return errors.New("no trace consumer available") } rs := td.ResourceSpans() for i := 0; i < rs.Len(); i++ { diff --git a/receiver/receivercreator/receiver.go b/receiver/receivercreator/receiver.go index c1aab76c9014..5715f40456c0 100644 --- a/receiver/receivercreator/receiver.go +++ b/receiver/receivercreator/receiver.go @@ -5,6 +5,7 @@ package receivercreator // import "github.com/open-telemetry/opentelemetry-colle import ( "context" + "errors" "fmt" "go.opentelemetry.io/collector/component" @@ -44,7 +45,7 @@ type host interface { func (rc *receiverCreator) Start(_ context.Context, h component.Host) error { rcHost, ok := h.(host) if !ok { - return fmt.Errorf("the receivercreator is not compatible with the provided component.host") + return errors.New("the receivercreator is not compatible with the provided component.host") } rc.observerHandler = &observerHandler{ diff --git a/receiver/sapmreceiver/factory.go b/receiver/sapmreceiver/factory.go index 8d2ded01073a..dabaa4a6871d 100644 --- a/receiver/sapmreceiver/factory.go +++ b/receiver/sapmreceiver/factory.go @@ -7,6 +7,7 @@ package sapmreceiver // import "github.com/open-telemetry/opentelemetry-collecto import ( "context" + "errors" "fmt" "net" "strconv" @@ -54,7 +55,7 @@ func extractPortFromEndpoint(endpoint string) (int, error) { return 0, fmt.Errorf("endpoint port is not a number: %w", err) } if port < 1 || port > 65535 { - return 0, fmt.Errorf("port number must be between 1 and 65535") + return 0, errors.New("port number must be between 1 and 65535") } return int(port), nil } diff --git a/receiver/signalfxreceiver/factory.go b/receiver/signalfxreceiver/factory.go index 87f71817f67d..a8ac397e3dd0 100644 --- a/receiver/signalfxreceiver/factory.go +++ b/receiver/signalfxreceiver/factory.go @@ -5,6 +5,7 @@ package signalfxreceiver // import "github.com/open-telemetry/opentelemetry-coll import ( "context" + "errors" "fmt" "net" "strconv" @@ -56,7 +57,7 @@ func extractPortFromEndpoint(endpoint string) (int, error) { return 0, fmt.Errorf("endpoint port is not a number: %w", err) } if port < 1 || port > 65535 { - return 0, fmt.Errorf("port number must be between 1 and 65535") + return 0, errors.New("port number must be between 1 and 65535") } return int(port), nil } diff --git a/receiver/skywalkingreceiver/config.go b/receiver/skywalkingreceiver/config.go index 02afbd1a8a43..ae94bbd19f70 100644 --- a/receiver/skywalkingreceiver/config.go +++ b/receiver/skywalkingreceiver/config.go @@ -4,6 +4,7 @@ package skywalkingreceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/skywalkingreceiver" import ( + "errors" "fmt" "go.opentelemetry.io/collector/component" @@ -34,7 +35,7 @@ var _ confmap.Unmarshaler = (*Config)(nil) // Validate checks the receiver configuration is valid func (cfg *Config) Validate() error { if cfg.GRPC == nil && cfg.HTTP == nil { - return fmt.Errorf("must specify at least one protocol when using the Skywalking receiver") + return errors.New("must specify at least one protocol when using the Skywalking receiver") } if cfg.GRPC != nil { @@ -56,7 +57,7 @@ func (cfg *Config) Validate() error { // Unmarshal a config.Parser into the config struct. func (cfg *Config) Unmarshal(componentParser *confmap.Conf) error { if componentParser == nil || len(componentParser.AllKeys()) == 0 { - return fmt.Errorf("empty config for Skywalking receiver") + return errors.New("empty config for Skywalking receiver") } // UnmarshalExact will not set struct properties to nil even if no key is provided, diff --git a/receiver/skywalkingreceiver/factory.go b/receiver/skywalkingreceiver/factory.go index 458bed44ad23..933e97ca06bd 100644 --- a/receiver/skywalkingreceiver/factory.go +++ b/receiver/skywalkingreceiver/factory.go @@ -7,6 +7,7 @@ package skywalkingreceiver // import "github.com/open-telemetry/opentelemetry-co import ( "context" + "errors" "fmt" "net" "strconv" @@ -146,7 +147,7 @@ func extractPortFromEndpoint(endpoint string) (int, error) { return 0, fmt.Errorf("endpoint port is not a number: %w", err) } if port < 1 || port > 65535 { - return 0, fmt.Errorf("port number must be between 1 and 65535") + return 0, errors.New("port number must be between 1 and 65535") } return int(port), nil } diff --git a/receiver/snmpreceiver/client_test.go b/receiver/snmpreceiver/client_test.go index 5bc38d09ad29..a4b3e881a13b 100644 --- a/receiver/snmpreceiver/client_test.go +++ b/receiver/snmpreceiver/client_test.go @@ -472,7 +472,7 @@ func TestGetScalarData(t *testing.T) { var scraperErrors scrapererror.ScrapeErrors oidSlice := []string{"1"} returnedSNMPData := client.GetScalarData(oidSlice, &scraperErrors) - expectedErr := fmt.Errorf("problem with getting scalar data: data for OID '1' not a supported type") + expectedErr := errors.New("problem with getting scalar data: data for OID '1' not a supported type") require.EqualError(t, scraperErrors.Combine(), expectedErr.Error()) require.Nil(t, returnedSNMPData) }, @@ -495,7 +495,7 @@ func TestGetScalarData(t *testing.T) { var scraperErrors scrapererror.ScrapeErrors oidSlice := []string{"1"} returnedSNMPData := client.GetScalarData(oidSlice, &scraperErrors) - expectedErr := fmt.Errorf("problem with getting scalar data: data for OID '1' not a supported type") + expectedErr := errors.New("problem with getting scalar data: data for OID '1' not a supported type") require.EqualError(t, scraperErrors.Combine(), expectedErr.Error()) require.Nil(t, returnedSNMPData) }, @@ -518,7 +518,7 @@ func TestGetScalarData(t *testing.T) { var scraperErrors scrapererror.ScrapeErrors oidSlice := []string{"1"} returnedSNMPData := client.GetScalarData(oidSlice, &scraperErrors) - expectedErr := fmt.Errorf("problem with getting scalar data: data for OID '1' not a supported type") + expectedErr := errors.New("problem with getting scalar data: data for OID '1' not a supported type") require.EqualError(t, scraperErrors.Combine(), expectedErr.Error()) require.Nil(t, returnedSNMPData) }, @@ -833,7 +833,7 @@ func TestGetIndexedData(t *testing.T) { } var scraperErrors scrapererror.ScrapeErrors returnedSNMPData := client.GetIndexedData([]string{"1"}, &scraperErrors) - expectedErr := fmt.Errorf("problem with getting indexed data: data for OID '1.1' not a supported type") + expectedErr := errors.New("problem with getting indexed data: data for OID '1.1' not a supported type") require.EqualError(t, scraperErrors.Combine(), expectedErr.Error()) require.Nil(t, returnedSNMPData) }, @@ -855,7 +855,7 @@ func TestGetIndexedData(t *testing.T) { } var scraperErrors scrapererror.ScrapeErrors returnedSNMPData := client.GetIndexedData([]string{"1"}, &scraperErrors) - expectedErr := fmt.Errorf("problem with getting indexed data: data for OID '1.1' not a supported type") + expectedErr := errors.New("problem with getting indexed data: data for OID '1.1' not a supported type") require.EqualError(t, scraperErrors.Combine(), expectedErr.Error()) require.Nil(t, returnedSNMPData) }, @@ -877,7 +877,7 @@ func TestGetIndexedData(t *testing.T) { } var scraperErrors scrapererror.ScrapeErrors returnedSNMPData := client.GetIndexedData([]string{"1"}, &scraperErrors) - expectedErr := fmt.Errorf("problem with getting indexed data: data for OID '1.1' not a supported type") + expectedErr := errors.New("problem with getting indexed data: data for OID '1.1' not a supported type") require.EqualError(t, scraperErrors.Combine(), expectedErr.Error()) require.Nil(t, returnedSNMPData) }, diff --git a/receiver/solacereceiver/messaging_service_test.go b/receiver/solacereceiver/messaging_service_test.go index 1179b1311647..60d7538378fe 100644 --- a/receiver/solacereceiver/messaging_service_test.go +++ b/receiver/solacereceiver/messaging_service_test.go @@ -7,7 +7,7 @@ import ( "bytes" "context" "crypto/tls" - "fmt" + "errors" "net" "reflect" "runtime" @@ -182,7 +182,7 @@ func TestNewAMQPMessagingServiceFactory(t *testing.T) { func TestAMQPDialFailure(t *testing.T) { const expectedAddr = "some-host:1234" - var expectedErr = fmt.Errorf("some error") + var expectedErr = errors.New("some error") dialFunc = func(_ context.Context, addr string, _ *amqp.ConnOptions) (*amqp.Conn, error) { defer func() { dialFunc = amqp.Dial }() // reset dialFunc assert.Equal(t, expectedAddr, addr) @@ -207,7 +207,7 @@ func TestAMQPDialFailure(t *testing.T) { func TestAMQPDialConfigOptionsWithoutTLS(t *testing.T) { // try creating a service without a tls config calling dial expecting no tls config passed const expectedAddr = "some-host:1234" - var expectedErr = fmt.Errorf("some error") + var expectedErr = errors.New("some error") expectedAuthConnOption := amqp.SASLTypeAnonymous() dialFunc = func(_ context.Context, addr string, opts *amqp.ConnOptions) (*amqp.Conn, error) { defer func() { dialFunc = amqp.Dial }() // reset dialFunc @@ -235,7 +235,7 @@ func TestAMQPDialConfigOptionsWithoutTLS(t *testing.T) { func TestAMQPDialConfigOptionsWithTLS(t *testing.T) { // try creating a service with a tls config calling dial const expectedAddr = "some-host:1234" - var expectedErr = fmt.Errorf("some error") + var expectedErr = errors.New("some error") expectedAuthConnOption := amqp.SASLTypeAnonymous() expectedTLSConnOption := &tls.Config{ InsecureSkipVerify: false, @@ -302,7 +302,7 @@ func TestAMQPNewClientDialAndCloseConnFailure(t *testing.T) { closed := false conn.setCloseHandler(func() error { closed = true - return fmt.Errorf("some error") + return errors.New("some error") }) service.close(context.Background()) // expect conn.Close to have been called diff --git a/receiver/solacereceiver/receiver.go b/receiver/solacereceiver/receiver.go index 4398008982c4..893c677bd69e 100644 --- a/receiver/solacereceiver/receiver.go +++ b/receiver/solacereceiver/receiver.go @@ -6,7 +6,6 @@ package solacereceiver // import "github.com/open-telemetry/opentelemetry-collec import ( "context" "errors" - "fmt" "sync" "sync/atomic" "time" @@ -283,7 +282,7 @@ flowControlLoop: case <-ctx.Done(): s.settings.Logger.Info("Context was cancelled while attempting redelivery, exiting") disposition = nil // do not make any network requests, we are shutting down - return fmt.Errorf("delayed retry interrupted by shutdown request") + return errors.New("delayed retry interrupted by shutdown request") } } else { // error is permanent, we want to accept the message and increment the number of dropped messages s.settings.Logger.Warn("Encountered permanent error while forwarding traces to next receiver, will swallow trace", zap.Error(forwardErr)) diff --git a/receiver/solacereceiver/receiver_test.go b/receiver/solacereceiver/receiver_test.go index 5b993b2797e9..d6ce7913ce2a 100644 --- a/receiver/solacereceiver/receiver_test.go +++ b/receiver/solacereceiver/receiver_test.go @@ -6,7 +6,6 @@ package solacereceiver // import "github.com/open-telemetry/opentelemetry-collec import ( "context" "errors" - "fmt" "runtime" "sync" "sync/atomic" @@ -660,7 +659,7 @@ func TestReceiverUnmarshalVersionFailureExpectingDisable(t *testing.T) { } func TestReceiverFlowControlDelayedRetry(t *testing.T) { - someError := consumererror.NewPermanent(fmt.Errorf("some error")) + someError := consumererror.NewPermanent(errors.New("some error")) testCases := []struct { name string nextConsumer consumer.Traces @@ -773,7 +772,7 @@ func TestReceiverFlowControlDelayedRetry(t *testing.T) { // we want to return an error at first, then set the next consumer to a noop consumer receiver.nextConsumer, err = consumer.NewTraces(func(context.Context, ptrace.Traces) error { receiver.nextConsumer = tc.nextConsumer - return fmt.Errorf("Some temporary error") + return errors.New("Some temporary error") }) require.NoError(t, err) @@ -953,7 +952,7 @@ func TestReceiverFlowControlDelayedRetryInterrupt(t *testing.T) { return nil }) require.NoError(t, err) - return fmt.Errorf("Some temporary error") + return errors.New("Some temporary error") }) require.NoError(t, err) @@ -1050,7 +1049,7 @@ func TestReceiverFlowControlDelayedRetryMultipleRetries(t *testing.T) { }) } require.NoError(t, err) - return fmt.Errorf("Some temporary error") + return errors.New("Some temporary error") }) require.NoError(t, err) diff --git a/receiver/solacereceiver/unmarshaller_egress_test.go b/receiver/solacereceiver/unmarshaller_egress_test.go index 3bde7f1b4d53..ecb40572b957 100644 --- a/receiver/solacereceiver/unmarshaller_egress_test.go +++ b/receiver/solacereceiver/unmarshaller_egress_test.go @@ -3,7 +3,7 @@ package solacereceiver import ( - "fmt" + "strconv" "testing" "github.com/Azure/go-amqp" @@ -285,7 +285,7 @@ func TestEgressUnmarshallerEgressSpan(t *testing.T) { } var i = 1 for _, dataRef := range validEgressSpans { - name := "valid span " + fmt.Sprint(i) + name := "valid span " + strconv.Itoa(i) i++ want := dataRef.out spanData := dataRef.in diff --git a/receiver/splunkhecreceiver/receiver_test.go b/receiver/splunkhecreceiver/receiver_test.go index e09e2abfaead..39553a0a7bcb 100644 --- a/receiver/splunkhecreceiver/receiver_test.go +++ b/receiver/splunkhecreceiver/receiver_test.go @@ -450,7 +450,7 @@ func Test_splunkhecReceiver_TLS(t *testing.T) { body, err := json.Marshal(buildSplunkHecMsg(sec, 0)) require.NoErrorf(t, err, "failed to marshal Splunk message: %v", err) - url := fmt.Sprintf("https://%s", addr) + url := "https://" + addr req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, url, bytes.NewReader(body)) require.NoErrorf(t, err, "should have no errors with new request: %v", err) @@ -1833,7 +1833,7 @@ func Test_splunkhecReceiver_rawReqHasmetadataInResource(t *testing.T) { for _, k := range []string{config.HecToOtelAttrs.Index, config.HecToOtelAttrs.SourceType, config.HecToOtelAttrs.Source, config.HecToOtelAttrs.Host} { v, ok := resource.Get(k) if !ok { - assert.Fail(t, fmt.Sprintf("does not contain query param: %s", k)) + assert.Fail(t, "does not contain query param: "+k) } assert.Equal(t, "bar", v.AsString()) } @@ -1858,7 +1858,7 @@ func Test_splunkhecReceiver_rawReqHasmetadataInResource(t *testing.T) { for _, k := range [2]string{config.HecToOtelAttrs.Index, config.HecToOtelAttrs.Source} { v, ok := resource.Get(k) if !ok { - assert.Fail(t, fmt.Sprintf("does not contain query param: %s", k)) + assert.Fail(t, "does not contain query param: "+k) } assert.Equal(t, "bar", v.AsString()) } diff --git a/receiver/sqlserverreceiver/config.go b/receiver/sqlserverreceiver/config.go index bdd79a5f935d..d44dc4a4a64b 100644 --- a/receiver/sqlserverreceiver/config.go +++ b/receiver/sqlserverreceiver/config.go @@ -4,7 +4,7 @@ package sqlserverreceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/sqlserverreceiver" import ( - "fmt" + "errors" "go.opentelemetry.io/collector/config/configopaque" "go.opentelemetry.io/collector/receiver/scraperhelper" @@ -35,7 +35,7 @@ func (cfg *Config) Validate() error { if !directDBConnectionEnabled(cfg) { if cfg.Server != "" || cfg.Username != "" || string(cfg.Password) != "" { - return fmt.Errorf("Found one or more of the following configuration options set: [server, port, username, password]. " + + return errors.New("Found one or more of the following configuration options set: [server, port, username, password]. " + "All of these options must be configured to directly connect to a SQL Server instance.") } } diff --git a/receiver/sqlserverreceiver/scraper_test.go b/receiver/sqlserverreceiver/scraper_test.go index dd1e4d654809..91ed9de2e1eb 100644 --- a/receiver/sqlserverreceiver/scraper_test.go +++ b/receiver/sqlserverreceiver/scraper_test.go @@ -6,7 +6,7 @@ package sqlserverreceiver import ( "context" "encoding/json" - "fmt" + "errors" "os" "path/filepath" "testing" @@ -179,7 +179,7 @@ func (mc mockClient) QueryRows(context.Context, ...any) ([]sqlquery.StringMap, e case getSQLServerPropertiesQuery(mc.instanceName): queryResults, err = readFile("propertyQueryData.txt") default: - return nil, fmt.Errorf("No valid query found") + return nil, errors.New("No valid query found") } if err != nil { diff --git a/receiver/sshcheckreceiver/internal/configssh/configssh.go b/receiver/sshcheckreceiver/internal/configssh/configssh.go index 8d5712cc1d21..cf13f1636059 100644 --- a/receiver/sshcheckreceiver/internal/configssh/configssh.go +++ b/receiver/sshcheckreceiver/internal/configssh/configssh.go @@ -55,7 +55,7 @@ func (c *Client) Dial(endpoint string) (err error) { func (c *Client) SFTPClient() (*SFTPClient, error) { if c.Client == nil || c.Client.Conn == nil { - return nil, fmt.Errorf("SSH client not initialized") + return nil, errors.New("SSH client not initialized") } client, err := sftp.NewClient(c.Client) if err != nil { @@ -135,7 +135,7 @@ func defaultKnownHostsPath() (string, error) { if err != nil { return "", err } - path := fmt.Sprintf("%s/.ssh/known_hosts", home) + path := home + "/.ssh/known_hosts" if _, err := os.Stat(path); err != nil { return "", errMissingKnownHosts } diff --git a/receiver/sshcheckreceiver/internal/configssh/configssh_test.go b/receiver/sshcheckreceiver/internal/configssh/configssh_test.go index 2b384653c4f5..77d418ca48e2 100644 --- a/receiver/sshcheckreceiver/internal/configssh/configssh_test.go +++ b/receiver/sshcheckreceiver/internal/configssh/configssh_test.go @@ -4,7 +4,7 @@ package configssh // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/sshcheckreceiver/internal/configssh" import ( - "fmt" + "errors" "testing" "time" @@ -164,7 +164,7 @@ func Test_Client_Dial(t *testing.T) { KeyFile: keyfile, }, dial: func(_, _ string, _ *ssh.ClientConfig) (*ssh.Client, error) { - return nil, fmt.Errorf("dial") + return nil, errors.New("dial") }, shouldError: true, }, @@ -237,7 +237,7 @@ func Test_Client_ToSFTPClient(t *testing.T) { KeyFile: keyfile, }, dial: func(_, _ string, _ *ssh.ClientConfig) (*ssh.Client, error) { - return nil, fmt.Errorf("dial") + return nil, errors.New("dial") }, shouldError: true, }, diff --git a/receiver/sshcheckreceiver/scraper_test.go b/receiver/sshcheckreceiver/scraper_test.go index 899d89bce5a9..074370b34445 100644 --- a/receiver/sshcheckreceiver/scraper_test.go +++ b/receiver/sshcheckreceiver/scraper_test.go @@ -6,7 +6,6 @@ package sshcheckreceiver // import "github.com/open-telemetry/opentelemetry-coll import ( "context" "errors" - "fmt" "io" "net" "os" @@ -49,7 +48,7 @@ func (s *sshServer) runSSHServer(t *testing.T) string { if c.User() == "otelu" && string(pass) == "otelp" { return nil, nil } - return nil, fmt.Errorf("wrong username or password") + return nil, errors.New("wrong username or password") }, } @@ -93,7 +92,7 @@ func (s *sshServer) shutdown() { func handleChannels(chans <-chan ssh.NewChannel) { for newChannel := range chans { if t := newChannel.ChannelType(); t != "session" { - if err := newChannel.Reject(ssh.UnknownChannelType, fmt.Sprintf("unknown channel type: %s", t)); err != nil { + if err := newChannel.Reject(ssh.UnknownChannelType, "unknown channel type: "+t); err != nil { return } continue diff --git a/receiver/statsdreceiver/config.go b/receiver/statsdreceiver/config.go index 92a6cc653b14..150c4aecd6ea 100644 --- a/receiver/statsdreceiver/config.go +++ b/receiver/statsdreceiver/config.go @@ -4,6 +4,7 @@ package statsdreceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/statsdreceiver" import ( + "errors" "fmt" "time" @@ -29,7 +30,7 @@ func (c *Config) Validate() error { var errs error if c.AggregationInterval <= 0 { - errs = multierr.Append(errs, fmt.Errorf("aggregation_interval must be a positive duration")) + errs = multierr.Append(errs, errors.New("aggregation_interval must be a positive duration")) } var TimerHistogramMappingMissingObjectName bool @@ -70,7 +71,7 @@ func (c *Config) Validate() error { // Non-histogram observer w/ histogram config var empty protocol.HistogramConfig if eachMap.Histogram != empty { - errs = multierr.Append(errs, fmt.Errorf("histogram configuration requires observer_type: histogram")) + errs = multierr.Append(errs, errors.New("histogram configuration requires observer_type: histogram")) } } if len(eachMap.Summary.Percentiles) != 0 { @@ -80,13 +81,13 @@ func (c *Config) Validate() error { } } if eachMap.ObserverType != protocol.SummaryObserver { - errs = multierr.Append(errs, fmt.Errorf("summary configuration requires observer_type: summary")) + errs = multierr.Append(errs, errors.New("summary configuration requires observer_type: summary")) } } } if TimerHistogramMappingMissingObjectName { - errs = multierr.Append(errs, fmt.Errorf("must specify object id for all TimerHistogramMappings")) + errs = multierr.Append(errs, errors.New("must specify object id for all TimerHistogramMappings")) } return errs diff --git a/receiver/statsdreceiver/internal/protocol/statsd_parser.go b/receiver/statsdreceiver/internal/protocol/statsd_parser.go index 8a2ad5237c77..1efb176e66ee 100644 --- a/receiver/statsdreceiver/internal/protocol/statsd_parser.go +++ b/receiver/statsdreceiver/internal/protocol/statsd_parser.go @@ -459,7 +459,7 @@ func parseMessageToMetric(line string, enableMetricType bool, enableSimpleTags b // As per DogStatD protocol v1.3: // https://docs.datadoghq.com/developers/dogstatsd/datagram_shell/?tab=metrics#dogstatsd-protocol-v13 if inType != CounterType && inType != GaugeType { - return result, fmt.Errorf("only GAUGE and COUNT metrics support a timestamp") + return result, errors.New("only GAUGE and COUNT metrics support a timestamp") } timestampStr := strings.TrimPrefix(part, "T") diff --git a/receiver/vcenterreceiver/processors.go b/receiver/vcenterreceiver/processors.go index f3f06fea5f46..b743d4b2cbf1 100644 --- a/receiver/vcenterreceiver/processors.go +++ b/receiver/vcenterreceiver/processors.go @@ -200,7 +200,7 @@ func (v *vcenterMetricScraper) buildHostMetrics( } if hs.Config == nil || hs.Config.VsanHostConfig == nil || hs.Config.VsanHostConfig.ClusterInfo == nil { - v.logger.Info(fmt.Sprintf("couldn't determine UUID necessary for vSAN metrics for host %s", hs.Name)) + v.logger.Info("couldn't determine UUID necessary for vSAN metrics for host " + hs.Name) v.mb.EmitForResource(metadata.WithResource(rb.Emit())) return vmRefToComputeRef, nil } @@ -383,7 +383,7 @@ func (v *vcenterMetricScraper) buildClusterMetrics( v.recordClusterStats(ts, cr, vmGroupInfo) vSANConfig := cr.ConfigurationEx.(*types.ClusterConfigInfoEx).VsanConfigInfo if vSANConfig == nil || vSANConfig.Enabled == nil || !*vSANConfig.Enabled || vSANConfig.DefaultConfig == nil { - v.logger.Info(fmt.Sprintf("couldn't determine UUID necessary for vSAN metrics for cluster %s", cr.Name)) + v.logger.Info("couldn't determine UUID necessary for vSAN metrics for cluster " + cr.Name) v.mb.EmitForResource(metadata.WithResource(rb.Emit())) return err } diff --git a/receiver/vcenterreceiver/scraper.go b/receiver/vcenterreceiver/scraper.go index e4b4bae52f37..9c1f395f2c99 100644 --- a/receiver/vcenterreceiver/scraper.go +++ b/receiver/vcenterreceiver/scraper.go @@ -92,7 +92,7 @@ func (v *vcenterMetricScraper) Start(ctx context.Context, _ component.Host) erro connectErr := v.client.EnsureConnection(ctx) // don't fail to start if we cannot establish connection, just log an error if connectErr != nil { - v.logger.Error(fmt.Sprintf("unable to establish a connection to the vSphere SDK %s", connectErr.Error())) + v.logger.Error("unable to establish a connection to the vSphere SDK " + connectErr.Error()) } return nil } diff --git a/receiver/windowseventlogreceiver/receiver_others.go b/receiver/windowseventlogreceiver/receiver_others.go index a14da170e37a..57b3aaec3f49 100644 --- a/receiver/windowseventlogreceiver/receiver_others.go +++ b/receiver/windowseventlogreceiver/receiver_others.go @@ -7,7 +7,7 @@ package windowseventlogreceiver // import "github.com/open-telemetry/opentelemet import ( "context" - "fmt" + "errors" "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/consumer" @@ -30,5 +30,5 @@ func createLogsReceiver( _ component.Config, _ consumer.Logs, ) (receiver.Logs, error) { - return nil, fmt.Errorf("windows eventlog receiver is only supported on Windows") + return nil, errors.New("windows eventlog receiver is only supported on Windows") } diff --git a/receiver/windowsperfcountersreceiver/config.go b/receiver/windowsperfcountersreceiver/config.go index a6b865fe7cd5..399d17dede8d 100644 --- a/receiver/windowsperfcountersreceiver/config.go +++ b/receiver/windowsperfcountersreceiver/config.go @@ -4,6 +4,7 @@ package windowsperfcountersreceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/windowsperfcountersreceiver" import ( + "errors" "fmt" "go.opentelemetry.io/collector/receiver/scraperhelper" @@ -57,11 +58,11 @@ func (c *Config) Validate() error { var errs error if c.CollectionInterval <= 0 { - errs = multierr.Append(errs, fmt.Errorf("collection_interval must be a positive duration")) + errs = multierr.Append(errs, errors.New("collection_interval must be a positive duration")) } if len(c.PerfCounters) == 0 { - errs = multierr.Append(errs, fmt.Errorf("must specify at least one perf counter")) + errs = multierr.Append(errs, errors.New("must specify at least one perf counter")) } for name, metric := range c.MetricMetaData { @@ -116,7 +117,7 @@ func (c *Config) Validate() error { } if perfCounterMissingObjectName { - errs = multierr.Append(errs, fmt.Errorf("must specify object name for all perf counters")) + errs = multierr.Append(errs, errors.New("must specify object name for all perf counters")) } return errs diff --git a/receiver/windowsperfcountersreceiver/config_test.go b/receiver/windowsperfcountersreceiver/config_test.go index db22ea8dc0a8..22d89d091ad7 100644 --- a/receiver/windowsperfcountersreceiver/config_test.go +++ b/receiver/windowsperfcountersreceiver/config_test.go @@ -181,7 +181,7 @@ func TestLoadConfig(t *testing.T) { }, { id: component.NewIDWithName(metadata.Type, "negative-collection-interval"), - expectedErr: fmt.Sprintf("collection_interval must be a positive duration; %s", negativeCollectionIntervalErr), + expectedErr: "collection_interval must be a positive duration; " + negativeCollectionIntervalErr, }, { id: component.NewIDWithName(metadata.Type, "noperfcounters"), diff --git a/receiver/zookeeperreceiver/scraper.go b/receiver/zookeeperreceiver/scraper.go index 44bbf5ae1b51..760072514900 100644 --- a/receiver/zookeeperreceiver/scraper.go +++ b/receiver/zookeeperreceiver/scraper.go @@ -164,7 +164,7 @@ func (z *zookeeperMetricsScraper) processMntr(response []string) { int64Val, err := strconv.ParseInt(metricValue, 10, 64) if err != nil { z.logger.Debug( - fmt.Sprintf("non-integer value from %s", mntrCommand), + "non-integer value from "+mntrCommand, zap.String("value", metricValue), ) continue diff --git a/receiver/zookeeperreceiver/scraper_test.go b/receiver/zookeeperreceiver/scraper_test.go index 4e643fdd5de3..cee0c9cacfea 100644 --- a/receiver/zookeeperreceiver/scraper_test.go +++ b/receiver/zookeeperreceiver/scraper_test.go @@ -7,7 +7,6 @@ import ( "bufio" "context" "errors" - "fmt" "net" "os" "path/filepath" @@ -328,7 +327,7 @@ func TestZookeeperMetricsScraperScrape(t *testing.T) { return } - expectedFile := filepath.Join("testdata", "scraper", fmt.Sprintf("%s.yaml", tt.expectedMetricsFilename)) + expectedFile := filepath.Join("testdata", "scraper", tt.expectedMetricsFilename+".yaml") expectedMetrics, err := golden.ReadMetrics(expectedFile) require.NoError(t, err)