From ead511174572e0bf1d1354da950791d4f6d97c02 Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Mon, 4 Nov 2024 08:02:27 +0100 Subject: [PATCH] [chore]: enable perfsprint linter Signed-off-by: Matthieu MOREL --- .golangci.yml | 13 ++++++++++++ cmd/mdatagen/internal/metadata.go | 5 +++-- component/componenttest/otelchecker.go | 10 +++++----- component/identifiable.go | 2 +- config/confighttp/compression_test.go | 3 +-- config/confighttp/compressor_test.go | 2 +- config/confighttp/confighttp_test.go | 7 ++++--- config/configopaque/opaque_test.go | 3 ++- config/configtls/clientcasfilereloader.go | 5 +++-- .../configtls/clientcasfilereloader_test.go | 2 +- config/configtls/configtls.go | 12 +++++------ confmap/confmap.go | 2 +- connector/internal/router.go | 3 ++- connector/logs_router.go | 3 ++- .../debugexporter/internal/normal/metrics.go | 3 ++- .../exporterhelper/internal/base_exporter.go | 6 +++--- .../internal/queue/persistent_queue_test.go | 4 ++-- exporter/otlphttpexporter/otlp_test.go | 20 +++++++++---------- featuregate/registry.go | 4 ++-- internal/e2e/otlphttp_test.go | 6 +++--- internal/testutil/testutil.go | 3 +-- otelcol/buffered_core.go | 4 ++-- pdata/pcommon/value.go | 2 +- pipeline/internal/globalsignal/signal.go | 3 ++- .../batchprocessor/batch_processor_test.go | 3 ++- .../internal/errors/errors_test.go | 6 +++--- service/service_test.go | 4 ++-- service/telemetry/config.go | 3 ++- service/telemetry/internal/otelinit/config.go | 9 +++++---- 29 files changed, 87 insertions(+), 65 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 7865174d156..ee0866e5e14 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -100,6 +100,18 @@ linters-settings: - kilometre - kilometres + perfsprint: + # Optimizes even if it requires an int or uint type cast. + int-conversion: true + # Optimizes into `err.Error()` even if it is only equivalent for non-nil errors. + err-error: true + # Optimizes `fmt.Errorf`. + errorf: true + # Optimizes `fmt.Sprintf` with only one argument. + sprintf1: true + # Optimizes into strings concatenation. + strconcat: true + depguard: rules: denied-deps: @@ -136,6 +148,7 @@ linters: - gosec - govet - misspell + - perfsprint - revive - staticcheck - tenv diff --git a/cmd/mdatagen/internal/metadata.go b/cmd/mdatagen/internal/metadata.go index 8a9fdba0d71..9348d7a12e8 100644 --- a/cmd/mdatagen/internal/metadata.go +++ b/cmd/mdatagen/internal/metadata.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "regexp" + "strconv" "strings" "go.opentelemetry.io/collector/filter" @@ -272,11 +273,11 @@ func (a Attribute) TestValue() string { case pcommon.ValueTypeStr: return fmt.Sprintf(`"%s-val"`, a.FullName) case pcommon.ValueTypeInt: - return fmt.Sprintf("%d", len(a.FullName)) + return strconv.Itoa(len(a.FullName)) case pcommon.ValueTypeDouble: return fmt.Sprintf("%f", 0.1+float64(len(a.FullName))) case pcommon.ValueTypeBool: - return fmt.Sprintf("%t", len(a.FullName)%2 == 0) + return strconv.FormatBool(len(a.FullName)%2 == 0) case pcommon.ValueTypeMap: return fmt.Sprintf(`map[string]any{"key1": "%s-val1", "key2": "%s-val2"}`, a.FullName, a.FullName) case pcommon.ValueTypeSlice: diff --git a/component/componenttest/otelchecker.go b/component/componenttest/otelchecker.go index 0c6b672dda7..c3196f7d66e 100644 --- a/component/componenttest/otelchecker.go +++ b/component/componenttest/otelchecker.go @@ -37,8 +37,8 @@ func checkReceiverMetrics(reader *sdkmetric.ManualReader, receiver component.ID, func checkReceiver(reader *sdkmetric.ManualReader, receiver component.ID, datatype, protocol string, acceptedMetricPoints, droppedMetricPoints int64) error { receiverAttrs := attributesForReceiverMetrics(receiver, protocol) return multierr.Combine( - checkIntSum(reader, fmt.Sprintf("otelcol_receiver_accepted_%s", datatype), acceptedMetricPoints, receiverAttrs), - checkIntSum(reader, fmt.Sprintf("otelcol_receiver_refused_%s", datatype), droppedMetricPoints, receiverAttrs)) + checkIntSum(reader, "otelcol_receiver_accepted_"+datatype, acceptedMetricPoints, receiverAttrs), + checkIntSum(reader, "otelcol_receiver_refused_"+datatype, droppedMetricPoints, receiverAttrs)) } func checkExporterTraces(reader *sdkmetric.ManualReader, exporter component.ID, sent, sendFailed int64) error { @@ -55,10 +55,10 @@ func checkExporterMetrics(reader *sdkmetric.ManualReader, exporter component.ID, func checkExporter(reader *sdkmetric.ManualReader, exporter component.ID, datatype string, sent, sendFailed int64) error { exporterAttrs := attributesForExporterMetrics(exporter) - errs := checkIntSum(reader, fmt.Sprintf("otelcol_exporter_sent_%s", datatype), sent, exporterAttrs) + errs := checkIntSum(reader, "otelcol_exporter_sent_"+datatype, sent, exporterAttrs) if sendFailed > 0 { errs = multierr.Append(errs, - checkIntSum(reader, fmt.Sprintf("otelcol_exporter_send_failed_%s", datatype), sendFailed, exporterAttrs)) + checkIntSum(reader, "otelcol_exporter_send_failed_"+datatype, sendFailed, exporterAttrs)) } return errs } @@ -68,7 +68,7 @@ func checkExporterEnqueueFailed(reader *sdkmetric.ManualReader, exporter compone return nil } exporterAttrs := attributesForExporterMetrics(exporter) - return checkIntSum(reader, fmt.Sprintf("otelcol_exporter_enqueue_failed_%s", datatype), enqueueFailed, exporterAttrs) + return checkIntSum(reader, "otelcol_exporter_enqueue_failed_"+datatype, enqueueFailed, exporterAttrs) } func checkIntGauge(reader *sdkmetric.ManualReader, metric string, expected int64, expectedAttrs attribute.Set) error { diff --git a/component/identifiable.go b/component/identifiable.go index 02869bdb7c4..aebacf087e1 100644 --- a/component/identifiable.go +++ b/component/identifiable.go @@ -48,7 +48,7 @@ func (t Type) MarshalText() ([]byte, error) { // - can only contain ASCII alphanumeric characters and '_'. func NewType(ty string) (Type, error) { if len(ty) == 0 { - return Type{}, fmt.Errorf("id must not be empty") + return Type{}, errors.New("id must not be empty") } if !typeRegexp.MatchString(ty) { return Type{}, fmt.Errorf("invalid character(s) in type %q", ty) diff --git a/config/confighttp/compression_test.go b/config/confighttp/compression_test.go index 870e9ba8371..e173f087af2 100644 --- a/config/confighttp/compression_test.go +++ b/config/confighttp/compression_test.go @@ -9,7 +9,6 @@ import ( "compress/zlib" "context" "errors" - "fmt" "io" "net/http" "net/http/httptest" @@ -335,7 +334,7 @@ type closeFailBody struct { } func (*closeFailBody) Close() error { - return fmt.Errorf("close failed") + return errors.New("close failed") } func TestHTTPContentCompressionRequestBodyCloseError(t *testing.T) { diff --git a/config/confighttp/compressor_test.go b/config/confighttp/compressor_test.go index 65e444578b4..90c140f25a6 100644 --- a/config/confighttp/compressor_test.go +++ b/config/confighttp/compressor_test.go @@ -46,7 +46,7 @@ func BenchmarkCompression(b *testing.B) { for i := range benchmarks { benchmark := &benchmarks[i] - b.Run(fmt.Sprint(benchmark.name), func(b *testing.B) { + b.Run(benchmark.name, func(b *testing.B) { benchmark.function(b, benchmark.codec, &buffer, payload) }) } diff --git a/config/confighttp/confighttp_test.go b/config/confighttp/confighttp_test.go index d9de4493e0b..f314fa96948 100644 --- a/config/confighttp/confighttp_test.go +++ b/config/confighttp/confighttp_test.go @@ -14,6 +14,7 @@ import ( "net/http/httptest" "net/url" "path/filepath" + "strconv" "strings" "testing" "time" @@ -813,7 +814,7 @@ func TestHttpCors(t *testing.T) { _ = s.Serve(ln) }() - url := fmt.Sprintf("http://%s", ln.Addr().String()) + url := "http://" + ln.Addr().String() expectedStatus := http.StatusNoContent if tt.CORSConfig == nil || len(tt.AllowedOrigins) == 0 { @@ -933,7 +934,7 @@ func TestHttpServerHeaders(t *testing.T) { _ = s.Serve(ln) }() - url := fmt.Sprintf("http://%s", ln.Addr().String()) + url := "http://" + ln.Addr().String() // Verify allowed domain gets responses that allow CORS. verifyHeadersResp(t, url, tt.headers) @@ -973,7 +974,7 @@ func verifyCorsResp(t *testing.T, url string, origin string, set *CORSConfig, ex wantAllowOrigin = origin wantAllowMethods = "POST" if set != nil && set.MaxAge != 0 { - wantMaxAge = fmt.Sprintf("%d", set.MaxAge) + wantMaxAge = strconv.Itoa(set.MaxAge) } } assert.Equal(t, wantAllowOrigin, gotAllowOrigin) diff --git a/config/configopaque/opaque_test.go b/config/configopaque/opaque_test.go index 044a5ea841c..09ebcab6bdc 100644 --- a/config/configopaque/opaque_test.go +++ b/config/configopaque/opaque_test.go @@ -5,6 +5,7 @@ package configopaque // import "go.opentelemetry.io/collector/config/configopaqu import ( "encoding" + "encoding/hex" "encoding/json" "fmt" "testing" @@ -69,7 +70,7 @@ func TestStringFmt(t *testing.T) { case "%q", "%#v": expected = "\"" + string(example) + "\"" case "%x": - expected = fmt.Sprintf("%x", []byte(example)) + expected = hex.EncodeToString([]byte(example)) default: t.Errorf("unexpected verb %q", verb) } diff --git a/config/configtls/clientcasfilereloader.go b/config/configtls/clientcasfilereloader.go index 1ee9c72ef9f..e6ca9b2962e 100644 --- a/config/configtls/clientcasfilereloader.go +++ b/config/configtls/clientcasfilereloader.go @@ -6,6 +6,7 @@ package configtls // import "go.opentelemetry.io/collector/config/configtls" import ( "crypto/tls" "crypto/x509" + "errors" "fmt" "sync" @@ -78,7 +79,7 @@ func (r *clientCAsFileReloader) getLastError() error { func (r *clientCAsFileReloader) startWatching() error { if r.shutdownCH != nil { - return fmt.Errorf("client CA file watcher already started") + return errors.New("client CA file watcher already started") } watcher, err := fsnotify.NewWatcher() @@ -132,7 +133,7 @@ func (r *clientCAsFileReloader) handleWatcherEvents() { func (r *clientCAsFileReloader) shutdown() error { if r.shutdownCH == nil { - return fmt.Errorf("client CAs file watcher is not running") + return errors.New("client CAs file watcher is not running") } r.shutdownCH <- true close(r.shutdownCH) diff --git a/config/configtls/clientcasfilereloader_test.go b/config/configtls/clientcasfilereloader_test.go index 074e0e72022..f5e7a1b0e39 100644 --- a/config/configtls/clientcasfilereloader_test.go +++ b/config/configtls/clientcasfilereloader_test.go @@ -68,7 +68,7 @@ func TestErrorRecordedIfFileDeleted(t *testing.T) { }, 5*time.Second, 10*time.Millisecond) lastErr := reloader.getLastError() - assert.Equal(t, "test error on reload", fmt.Sprint(lastErr)) + require.EqualError(t, lastErr, "test error on reload") err = reloader.shutdown() assert.NoError(t, err) diff --git a/config/configtls/configtls.go b/config/configtls/configtls.go index 2ce0490b16c..0cbcc5f4072 100644 --- a/config/configtls/configtls.go +++ b/config/configtls/configtls.go @@ -179,7 +179,7 @@ func (r *certReloader) GetCertificate() (*tls.Certificate, error) { func (c Config) Validate() error { if c.hasCAFile() && c.hasCAPem() { - return fmt.Errorf("provide either a CA file or the PEM-encoded string, but not both") + return errors.New("provide either a CA file or the PEM-encoded string, but not both") } minTLS, err := convertVersion(c.MinVersion, defaultMinTLSVersion) @@ -269,7 +269,7 @@ func (c Config) loadCACertPool() (*x509.CertPool, error) { switch { case c.hasCAFile() && c.hasCAPem(): - return nil, fmt.Errorf("failed to load CA CertPool: provide either a CA file or the PEM-encoded string, but not both") + return nil, errors.New("failed to load CA CertPool: provide either a CA file or the PEM-encoded string, but not both") case c.hasCAFile(): // Set up user specified truststore from file certPool, err = c.loadCertFile(c.CAFile) @@ -308,7 +308,7 @@ func (c Config) loadCertPem(certPem []byte) (*x509.CertPool, error) { } } if !certPool.AppendCertsFromPEM(certPem) { - return nil, fmt.Errorf("failed to parse cert") + return nil, errors.New("failed to parse cert") } return certPool, nil } @@ -316,13 +316,13 @@ func (c Config) loadCertPem(certPem []byte) (*x509.CertPool, error) { func (c Config) loadCertificate() (tls.Certificate, error) { switch { case c.hasCert() != c.hasKey(): - return tls.Certificate{}, fmt.Errorf("for auth via TLS, provide both certificate and key, or neither") + return tls.Certificate{}, errors.New("for auth via TLS, provide both certificate and key, or neither") case !c.hasCert() && !c.hasKey(): return tls.Certificate{}, nil case c.hasCertFile() && c.hasCertPem(): - return tls.Certificate{}, fmt.Errorf("for auth via TLS, provide either a certificate or the PEM-encoded string, but not both") + return tls.Certificate{}, errors.New("for auth via TLS, provide either a certificate or the PEM-encoded string, but not both") case c.hasKeyFile() && c.hasKeyPem(): - return tls.Certificate{}, fmt.Errorf("for auth via TLS, provide either a key or the PEM-encoded string, but not both") + return tls.Certificate{}, errors.New("for auth via TLS, provide either a key or the PEM-encoded string, but not both") } var certPem, keyPem []byte diff --git a/confmap/confmap.go b/confmap/confmap.go index 0a8a3461159..a7a99d10352 100644 --- a/confmap/confmap.go +++ b/confmap/confmap.go @@ -102,7 +102,7 @@ func (l *Conf) Marshal(rawVal any, _ ...MarshalOption) error { } out, ok := data.(map[string]any) if !ok { - return fmt.Errorf("invalid config encoding") + return errors.New("invalid config encoding") } return l.Merge(NewFromStringMap(out)) } diff --git a/connector/internal/router.go b/connector/internal/router.go index 9360ff948a8..e951abd134f 100644 --- a/connector/internal/router.go +++ b/connector/internal/router.go @@ -4,6 +4,7 @@ package internal // import "go.opentelemetry.io/collector/connector/internal" import ( + "errors" "fmt" "go.uber.org/multierr" @@ -35,7 +36,7 @@ func (r *BaseRouter[T]) PipelineIDs() []pipeline.ID { func (r *BaseRouter[T]) Consumer(pipelineIDs ...pipeline.ID) (T, error) { var ret T if len(pipelineIDs) == 0 { - return ret, fmt.Errorf("missing consumers") + return ret, errors.New("missing consumers") } consumers := make([]T, 0, len(pipelineIDs)) var errors error diff --git a/connector/logs_router.go b/connector/logs_router.go index ff6190aa643..a2d74de29a3 100644 --- a/connector/logs_router.go +++ b/connector/logs_router.go @@ -4,6 +4,7 @@ package connector // import "go.opentelemetry.io/collector/connector" import ( + "errors" "fmt" "go.uber.org/multierr" @@ -48,7 +49,7 @@ func (r *logsRouter) PipelineIDs() []pipeline.ID { func (r *logsRouter) Consumer(pipelineIDs ...pipeline.ID) (consumer.Logs, error) { if len(pipelineIDs) == 0 { - return nil, fmt.Errorf("missing consumers") + return nil, errors.New("missing consumers") } consumers := make([]consumer.Logs, 0, len(pipelineIDs)) var errors error diff --git a/exporter/debugexporter/internal/normal/metrics.go b/exporter/debugexporter/internal/normal/metrics.go index c8e8eca17d6..582656064ed 100644 --- a/exporter/debugexporter/internal/normal/metrics.go +++ b/exporter/debugexporter/internal/normal/metrics.go @@ -6,6 +6,7 @@ package normal // import "go.opentelemetry.io/collector/exporter/debugexporter/i import ( "bytes" "fmt" + "strconv" "strings" "go.opentelemetry.io/collector/pdata/pmetric" @@ -60,7 +61,7 @@ func writeNumberDataPoints(metric pmetric.Metric, dataPoints pmetric.NumberDataP var value string switch dataPoint.ValueType() { case pmetric.NumberDataPointValueTypeInt: - value = fmt.Sprintf("%v", dataPoint.IntValue()) + value = strconv.FormatInt(dataPoint.IntValue(), 10) case pmetric.NumberDataPointValueTypeDouble: value = fmt.Sprintf("%v", dataPoint.DoubleValue()) } diff --git a/exporter/exporterhelper/internal/base_exporter.go b/exporter/exporterhelper/internal/base_exporter.go index 763972e793e..f3c4e67113b 100644 --- a/exporter/exporterhelper/internal/base_exporter.go +++ b/exporter/exporterhelper/internal/base_exporter.go @@ -5,7 +5,7 @@ package internal // import "go.opentelemetry.io/collector/exporter/exporterhelpe import ( "context" - "fmt" + "errors" "testing" "github.com/stretchr/testify/require" @@ -214,7 +214,7 @@ func WithRetry(config configretry.BackOffConfig) Option { func WithQueue(config QueueConfig) Option { return func(o *BaseExporter) error { if o.Marshaler == nil || o.Unmarshaler == nil { - return fmt.Errorf("WithQueue option is not available for the new request exporters, use WithRequestQueue instead") + return errors.New("WithQueue option is not available for the new request exporters, use WithRequestQueue instead") } if !config.Enabled { o.ExportFailureMessage += " Try enabling sending_queue to survive temporary failures." @@ -240,7 +240,7 @@ func WithQueue(config QueueConfig) Option { func WithRequestQueue(cfg exporterqueue.Config, queueFactory exporterqueue.Factory[internal.Request]) Option { return func(o *BaseExporter) error { if o.Marshaler != nil || o.Unmarshaler != nil { - return fmt.Errorf("WithRequestQueue option must be used with the new request exporters only, use WithQueue instead") + return errors.New("WithRequestQueue option must be used with the new request exporters only, use WithQueue instead") } if !cfg.Enabled { o.ExportFailureMessage += " Try enabling sending_queue to survive temporary failures." diff --git a/exporter/internal/queue/persistent_queue_test.go b/exporter/internal/queue/persistent_queue_test.go index c453b2d760a..c6b19e0f2ad 100644 --- a/exporter/internal/queue/persistent_queue_test.go +++ b/exporter/internal/queue/persistent_queue_test.go @@ -802,8 +802,8 @@ func TestPersistentQueue_StorageFull(t *testing.T) { } func TestPersistentQueue_ItemDispatchingFinish_ErrorHandling(t *testing.T) { - errDeletingItem := fmt.Errorf("error deleting item") - errUpdatingDispatched := fmt.Errorf("error updating dispatched items") + errDeletingItem := errors.New("error deleting item") + errUpdatingDispatched := errors.New("error updating dispatched items") testCases := []struct { storageErrors []error expectedError error diff --git a/exporter/otlphttpexporter/otlp_test.go b/exporter/otlphttpexporter/otlp_test.go index 71ebe5d15c6..65a2e5bacc7 100644 --- a/exporter/otlphttpexporter/otlp_test.go +++ b/exporter/otlphttpexporter/otlp_test.go @@ -225,7 +225,7 @@ func TestErrorResponses(t *testing.T) { cfg := &Config{ Encoding: EncodingProto, - TracesEndpoint: fmt.Sprintf("%s/v1/traces", srv.URL), + TracesEndpoint: srv.URL + "/v1/traces", // Create without QueueConfig and RetryConfig so that ConsumeTraces // returns the errors that we want to check immediately. } @@ -300,7 +300,7 @@ func TestUserAgent(t *testing.T) { cfg := &Config{ Encoding: EncodingProto, - TracesEndpoint: fmt.Sprintf("%s/v1/traces", srv.URL), + TracesEndpoint: srv.URL + "/v1/traces", ClientConfig: confighttp.ClientConfig{ Headers: tt.headers, }, @@ -334,7 +334,7 @@ func TestUserAgent(t *testing.T) { cfg := &Config{ Encoding: EncodingProto, - MetricsEndpoint: fmt.Sprintf("%s/v1/metrics", srv.URL), + MetricsEndpoint: srv.URL + "/v1/metrics", ClientConfig: confighttp.ClientConfig{ Headers: tt.headers, }, @@ -368,7 +368,7 @@ func TestUserAgent(t *testing.T) { cfg := &Config{ Encoding: EncodingProto, - LogsEndpoint: fmt.Sprintf("%s/v1/logs", srv.URL), + LogsEndpoint: srv.URL + "/v1/logs", ClientConfig: confighttp.ClientConfig{ Headers: tt.headers, }, @@ -521,7 +521,7 @@ func TestPartialSuccess_logs(t *testing.T) { cfg := &Config{ Encoding: EncodingProto, - LogsEndpoint: fmt.Sprintf("%s/v1/logs", srv.URL), + LogsEndpoint: srv.URL + "/v1/logs", ClientConfig: confighttp.ClientConfig{}, } set := exportertest.NewNopSettings() @@ -881,7 +881,7 @@ func TestPartialSuccess_traces(t *testing.T) { cfg := &Config{ Encoding: EncodingProto, - TracesEndpoint: fmt.Sprintf("%s/v1/traces", srv.URL), + TracesEndpoint: srv.URL + "/v1/traces", ClientConfig: confighttp.ClientConfig{}, } set := exportertest.NewNopSettings() @@ -921,7 +921,7 @@ func TestPartialSuccess_metrics(t *testing.T) { cfg := &Config{ Encoding: EncodingProto, - MetricsEndpoint: fmt.Sprintf("%s/v1/metrics", srv.URL), + MetricsEndpoint: srv.URL + "/v1/metrics", ClientConfig: confighttp.ClientConfig{}, } set := exportertest.NewNopSettings() @@ -1018,7 +1018,7 @@ func TestEncoding(t *testing.T) { defer srv.Close() cfg := &Config{ - TracesEndpoint: fmt.Sprintf("%s/v1/traces", srv.URL), + TracesEndpoint: srv.URL + "/v1/traces", Encoding: tt.encoding, } exp, err := createTraces(context.Background(), set, cfg) @@ -1049,7 +1049,7 @@ func TestEncoding(t *testing.T) { defer srv.Close() cfg := &Config{ - MetricsEndpoint: fmt.Sprintf("%s/v1/metrics", srv.URL), + MetricsEndpoint: srv.URL + "/v1/metrics", Encoding: tt.encoding, } exp, err := createMetrics(context.Background(), set, cfg) @@ -1080,7 +1080,7 @@ func TestEncoding(t *testing.T) { defer srv.Close() cfg := &Config{ - LogsEndpoint: fmt.Sprintf("%s/v1/logs", srv.URL), + LogsEndpoint: srv.URL + "/v1/logs", Encoding: tt.encoding, } exp, err := createLogs(context.Background(), set, cfg) diff --git a/featuregate/registry.go b/featuregate/registry.go index 69486d623ee..a72e51a610d 100644 --- a/featuregate/registry.go +++ b/featuregate/registry.go @@ -118,11 +118,11 @@ func (r *Registry) MustRegister(id string, stage Stage, opts ...RegisterOption) func validateID(id string) error { if id == "" { - return fmt.Errorf("empty ID") + return errors.New("empty ID") } if !idRegexp.MatchString(id) { - return fmt.Errorf("invalid character(s) in ID") + return errors.New("invalid character(s) in ID") } return nil } diff --git a/internal/e2e/otlphttp_test.go b/internal/e2e/otlphttp_test.go index 9da34e260aa..be36e8b5ccc 100644 --- a/internal/e2e/otlphttp_test.go +++ b/internal/e2e/otlphttp_test.go @@ -94,7 +94,7 @@ func TestTraceRoundTrip(t *testing.T) { }, { name: "onlybase", - baseURL: fmt.Sprintf("http://%s", addr), + baseURL: "http://" + addr, overrideURL: "", }, { @@ -147,7 +147,7 @@ func TestMetricsRoundTrip(t *testing.T) { }, { name: "onlybase", - baseURL: fmt.Sprintf("http://%s", addr), + baseURL: "http://" + addr, overrideURL: "", }, { @@ -200,7 +200,7 @@ func TestLogsRoundTrip(t *testing.T) { }, { name: "onlybase", - baseURL: fmt.Sprintf("http://%s", addr), + baseURL: "http://" + addr, overrideURL: "", }, { diff --git a/internal/testutil/testutil.go b/internal/testutil/testutil.go index 8d0882d04e6..5af973dd1b4 100644 --- a/internal/testutil/testutil.go +++ b/internal/testutil/testutil.go @@ -4,7 +4,6 @@ package testutil // import "go.opentelemetry.io/collector/internal/testutil" import ( - "fmt" "net" "os/exec" "runtime" @@ -74,7 +73,7 @@ func findAvailableAddress(network string, t testing.TB) string { } require.NotZero(t, host, "network must be either of tcp, tcp4 or tcp6") - ln, err := net.Listen("tcp", fmt.Sprintf("%s:0", host)) + ln, err := net.Listen("tcp", host+":0") require.NoError(t, err, "Failed to get a free local port") // There is a possible race if something else takes this same port before // the test uses it, however, that is unlikely in practice. diff --git a/otelcol/buffered_core.go b/otelcol/buffered_core.go index 447bf13cb52..dd334a8454e 100644 --- a/otelcol/buffered_core.go +++ b/otelcol/buffered_core.go @@ -6,7 +6,7 @@ package otelcol // import "go.opentelemetry.io/collector/otelcol" import ( - "fmt" + "errors" "sync" "go.uber.org/zap/zapcore" @@ -55,7 +55,7 @@ func (bc *bufferedCore) Write(ent zapcore.Entry, fields []zapcore.Field) error { bc.mu.Lock() defer bc.mu.Unlock() if bc.logsTaken { - return fmt.Errorf("the buffered logs have already been taken so writing is no longer supported") + return errors.New("the buffered logs have already been taken so writing is no longer supported") } all := make([]zapcore.Field, 0, len(fields)+len(bc.context)) all = append(all, bc.context...) diff --git a/pdata/pcommon/value.go b/pdata/pcommon/value.go index 286b9c928e3..ad2e1c7ae47 100644 --- a/pdata/pcommon/value.go +++ b/pdata/pcommon/value.go @@ -403,7 +403,7 @@ func (v Value) AsString() string { // This allows us to avoid using reflection. func float64AsString(f float64) string { if math.IsInf(f, 0) || math.IsNaN(f) { - return fmt.Sprintf("json: unsupported value: %s", strconv.FormatFloat(f, 'g', -1, 64)) + return "json: unsupported value: " + strconv.FormatFloat(f, 'g', -1, 64) } // Convert as if by ES6 number to string conversion. diff --git a/pipeline/internal/globalsignal/signal.go b/pipeline/internal/globalsignal/signal.go index c97f7913075..dd7c6ec623c 100644 --- a/pipeline/internal/globalsignal/signal.go +++ b/pipeline/internal/globalsignal/signal.go @@ -4,6 +4,7 @@ package globalsignal // import "go.opentelemetry.io/collector/pipeline/internal/globalsignal" import ( + "errors" "fmt" "regexp" ) @@ -31,7 +32,7 @@ var signalRegex = regexp.MustCompile(`^[a-z]{1,62}$`) // A Signal must consist of 1 to 62 lowercase ASCII alphabetic characters. func NewSignal(signal string) (Signal, error) { if len(signal) == 0 { - return Signal{}, fmt.Errorf("signal must not be empty") + return Signal{}, errors.New("signal must not be empty") } if !signalRegex.MatchString(signal) { return Signal{}, fmt.Errorf("invalid character(s) in type %q", signal) diff --git a/processor/batchprocessor/batch_processor_test.go b/processor/batchprocessor/batch_processor_test.go index a054bc008bc..691c906eb33 100644 --- a/processor/batchprocessor/batch_processor_test.go +++ b/processor/batchprocessor/batch_processor_test.go @@ -7,6 +7,7 @@ import ( "context" "fmt" "math" + "strconv" "sync" "testing" "time" @@ -1302,7 +1303,7 @@ func TestBatchProcessorMetadataCardinalityLimit(t *testing.T) { td := testdata.GenerateTraces(1) ctx := client.NewContext(bg, client.Info{ Metadata: client.NewMetadata(map[string][]string{ - "token": {fmt.Sprint(requestNum)}, + "token": {strconv.Itoa(requestNum)}, }), }) diff --git a/receiver/otlpreceiver/internal/errors/errors_test.go b/receiver/otlpreceiver/internal/errors/errors_test.go index b56966bc441..2ba1631a22e 100644 --- a/receiver/otlpreceiver/internal/errors/errors_test.go +++ b/receiver/otlpreceiver/internal/errors/errors_test.go @@ -4,7 +4,7 @@ package errors // import "go.opentelemetry.io/collector/receiver/otlpreceiver/internal/util" import ( - "fmt" + "errors" "net/http" "testing" @@ -28,12 +28,12 @@ func Test_GetStatusFromError(t *testing.T) { }, { name: "Permanent Error", - input: consumererror.NewPermanent(fmt.Errorf("test")), + input: consumererror.NewPermanent(errors.New("test")), expected: status.New(codes.Internal, "Permanent error: test"), }, { name: "Non-Permanent Error", - input: fmt.Errorf("test"), + input: errors.New("test"), expected: status.New(codes.Unavailable, "test"), }, } diff --git a/service/service_test.go b/service/service_test.go index 1b7b1eca704..fb30d7a8fcb 100644 --- a/service/service_test.go +++ b/service/service_test.go @@ -263,10 +263,10 @@ func TestServiceTelemetryCleanupOnError(t *testing.T) { func TestServiceTelemetry(t *testing.T) { for _, tc := range ownMetricsTestCases() { - t.Run(fmt.Sprintf("ipv4_%s", tc.name), func(t *testing.T) { + t.Run("ipv4_"+tc.name, func(t *testing.T) { testCollectorStartHelperWithReaders(t, tc, "tcp4") }) - t.Run(fmt.Sprintf("ipv6_%s", tc.name), func(t *testing.T) { + t.Run("ipv6_"+tc.name, func(t *testing.T) { testCollectorStartHelperWithReaders(t, tc, "tcp6") }) } diff --git a/service/telemetry/config.go b/service/telemetry/config.go index 15f647386c9..e6d80dbd16c 100644 --- a/service/telemetry/config.go +++ b/service/telemetry/config.go @@ -4,6 +4,7 @@ package telemetry // import "go.opentelemetry.io/collector/service/telemetry" import ( + "errors" "fmt" "net" "strconv" @@ -205,7 +206,7 @@ func (c *Config) Unmarshal(conf *confmap.Conf) error { func (c *Config) Validate() error { // Check when service telemetry metric level is not none, the metrics readers should not be empty if c.Metrics.Level != configtelemetry.LevelNone && len(c.Metrics.Readers) == 0 { - return fmt.Errorf("collector telemetry metrics reader should exist when metric level is not none") + return errors.New("collector telemetry metrics reader should exist when metric level is not none") } return nil diff --git a/service/telemetry/internal/otelinit/config.go b/service/telemetry/internal/otelinit/config.go index a8983886038..402090675ac 100644 --- a/service/telemetry/internal/otelinit/config.go +++ b/service/telemetry/internal/otelinit/config.go @@ -12,6 +12,7 @@ import ( "net/http" "net/url" "os" + "strconv" "strings" "sync" "time" @@ -142,10 +143,10 @@ func cardinalityFilter(filter attribute.Set) attribute.Filter { func initPrometheusExporter(prometheusConfig *config.Prometheus, asyncErrorChannel chan error, serverWG *sync.WaitGroup) (sdkmetric.Reader, *http.Server, error) { promRegistry := prometheus.NewRegistry() if prometheusConfig.Host == nil { - return nil, nil, fmt.Errorf("host must be specified") + return nil, nil, errors.New("host must be specified") } if prometheusConfig.Port == nil { - return nil, nil, fmt.Errorf("port must be specified") + return nil, nil, errors.New("port must be specified") } opts := []otelprom.Option{ @@ -163,7 +164,7 @@ func initPrometheusExporter(prometheusConfig *config.Prometheus, asyncErrorChann return nil, nil, fmt.Errorf("error creating otel prometheus exporter: %w", err) } - return exporter, InitPrometheusServer(promRegistry, net.JoinHostPort(*prometheusConfig.Host, fmt.Sprintf("%d", *prometheusConfig.Port)), asyncErrorChannel, serverWG), nil + return exporter, InitPrometheusServer(promRegistry, net.JoinHostPort(*prometheusConfig.Host, strconv.Itoa(*prometheusConfig.Port)), asyncErrorChannel, serverWG), nil } func initPullExporter(exporter config.MetricExporter, asyncErrorChannel chan error, serverWG *sync.WaitGroup) (sdkmetric.Reader, *http.Server, error) { @@ -207,7 +208,7 @@ func initPeriodicExporter(ctx context.Context, exporter config.MetricExporter, o func normalizeEndpoint(endpoint string) string { if !strings.HasPrefix(endpoint, "https://") && !strings.HasPrefix(endpoint, "http://") { - return fmt.Sprintf("http://%s", endpoint) + return "http://" + endpoint } return endpoint }