diff --git a/exporter/alertmanagerexporter/alertmanager_exporter.go b/exporter/alertmanagerexporter/alertmanager_exporter.go index 250fc5877147..58a8ba393c73 100644 --- a/exporter/alertmanagerexporter/alertmanager_exporter.go +++ b/exporter/alertmanagerexporter/alertmanager_exporter.go @@ -167,7 +167,6 @@ func (s *alertmanagerExporter) pushTraces(ctx context.Context, td ptrace.Traces) alert := s.convertEventsToAlertPayload(events) err := s.postAlert(ctx, alert) - if err != nil { return err } diff --git a/exporter/alertmanagerexporter/config_test.go b/exporter/alertmanagerexporter/config_test.go index e884e0c17755..07802fbc3e5a 100644 --- a/exporter/alertmanagerexporter/config_test.go +++ b/exporter/alertmanagerexporter/config_test.go @@ -37,7 +37,6 @@ func TestLoadConfig(t *testing.T) { id component.ID expected component.Config }{ - { id: component.NewIDWithName(metadata.Type, ""), expected: defaultCfg, diff --git a/exporter/alibabacloudlogserviceexporter/config_test.go b/exporter/alibabacloudlogserviceexporter/config_test.go index a9ce04f83909..3af84173c7dd 100644 --- a/exporter/alibabacloudlogserviceexporter/config_test.go +++ b/exporter/alibabacloudlogserviceexporter/config_test.go @@ -29,7 +29,6 @@ func TestLoadConfig(t *testing.T) { id component.ID expected component.Config }{ - { id: component.NewIDWithName(metadata.Type, ""), expected: defaultCfg, diff --git a/exporter/alibabacloudlogserviceexporter/logs_exporter.go b/exporter/alibabacloudlogserviceexporter/logs_exporter.go index e6f9668491b8..33eaf37e5230 100644 --- a/exporter/alibabacloudlogserviceexporter/logs_exporter.go +++ b/exporter/alibabacloudlogserviceexporter/logs_exporter.go @@ -38,7 +38,8 @@ type logServiceLogsSender struct { func (s *logServiceLogsSender) pushLogsData( _ context.Context, - md plog.Logs) error { + md plog.Logs, +) error { var err error slsLogs := logDataToLogService(md) if len(slsLogs) > 0 { diff --git a/exporter/alibabacloudlogserviceexporter/logsdata_to_logservice.go b/exporter/alibabacloudlogserviceexporter/logsdata_to_logservice.go index 29b11ca37457..5fc5058bfc19 100644 --- a/exporter/alibabacloudlogserviceexporter/logsdata_to_logservice.go +++ b/exporter/alibabacloudlogserviceexporter/logsdata_to_logservice.go @@ -115,7 +115,8 @@ func instrumentationScopeToLogContents(instrumentationScope pcommon.Instrumentat func mapLogRecordToLogService(lr plog.LogRecord, resourceContents, - instrumentationLibraryContents []*sls.LogContent) *sls.Log { + instrumentationLibraryContents []*sls.LogContent, +) *sls.Log { if lr.Body().Type() == pcommon.ValueTypeEmpty { return nil } diff --git a/exporter/alibabacloudlogserviceexporter/metricsdata_to_logservice.go b/exporter/alibabacloudlogserviceexporter/metricsdata_to_logservice.go index a9f4c23a1462..c01e83447400 100644 --- a/exporter/alibabacloudlogserviceexporter/metricsdata_to_logservice.go +++ b/exporter/alibabacloudlogserviceexporter/metricsdata_to_logservice.go @@ -113,7 +113,8 @@ func newMetricLogFromRaw( name string, labels KeyValues, nsec int64, - value float64) *sls.Log { + value float64, +) *sls.Log { labels.Sort() return &sls.Log{ Time: proto.Uint32(uint32(nsec / 1e9)), diff --git a/exporter/awscloudwatchlogsexporter/exporter.go b/exporter/awscloudwatchlogsexporter/exporter.go index 03056439b75f..9aa14be1e3de 100644 --- a/exporter/awscloudwatchlogsexporter/exporter.go +++ b/exporter/awscloudwatchlogsexporter/exporter.go @@ -63,7 +63,6 @@ func newCwLogsPusher(expConfig *Config, params exp.Settings) (*cwlExporter, erro // create CWLogs client with aws session config svcStructuredLog := cwlogs.NewClient(params.Logger, awsConfig, params.BuildInfo, expConfig.LogGroupName, expConfig.LogRetention, expConfig.Tags, session, metadata.Type.String()) collectorIdentifier, err := uuid.NewRandom() - if err != nil { return nil, err } @@ -105,13 +104,11 @@ func (e *cwlExporter) consumeLogs(_ context.Context, ld plog.Logs) error { var errs error err := pushLogsToCWLogs(e.logger, ld, e.Config, pusher) - if err != nil { errs = errors.Join(errs, fmt.Errorf("Error pushing logs: %w", err)) } err = pusher.ForceFlush() - if err != nil { errs = errors.Join(errs, fmt.Errorf("Error flushing logs: %w", err)) } diff --git a/exporter/awsemfexporter/config.go b/exporter/awsemfexporter/config.go index 969a69e67798..7495277e1c2a 100644 --- a/exporter/awsemfexporter/config.go +++ b/exporter/awsemfexporter/config.go @@ -14,11 +14,9 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/resourcetotelemetry" ) -var ( - // eMFSupportedUnits contains the unit collection supported by CloudWatch backend service. - // https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html - eMFSupportedUnits = newEMFSupportedUnits() -) +// eMFSupportedUnits contains the unit collection supported by CloudWatch backend service. +// https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html +var eMFSupportedUnits = newEMFSupportedUnits() // Config defines configuration for AWS EMF exporter. type Config struct { @@ -152,11 +150,13 @@ func (config *Config) isAppSignalsEnabled() bool { func newEMFSupportedUnits() map[string]any { unitIndexer := map[string]any{} - for _, unit := range []string{"Seconds", "Microseconds", "Milliseconds", "Bytes", "Kilobytes", "Megabytes", + for _, unit := range []string{ + "Seconds", "Microseconds", "Milliseconds", "Bytes", "Kilobytes", "Megabytes", "Gigabytes", "Terabytes", "Bits", "Kilobits", "Megabits", "Gigabits", "Terabits", "Percent", "Count", "Bytes/Second", "Kilobytes/Second", "Megabytes/Second", "Gigabytes/Second", "Terabytes/Second", "Bits/Second", "Kilobits/Second", - "Megabits/Second", "Gigabits/Second", "Terabits/Second", "Count/Second", "None"} { + "Megabits/Second", "Gigabits/Second", "Terabits/Second", "Count/Second", "None", + } { unitIndexer[unit] = nil } return unitIndexer diff --git a/exporter/awsemfexporter/datapoint_test.go b/exporter/awsemfexporter/datapoint_test.go index 46ba057c036e..911ecc48e24e 100644 --- a/exporter/awsemfexporter/datapoint_test.go +++ b/exporter/awsemfexporter/datapoint_test.go @@ -333,6 +333,7 @@ func generateOtelTestMetrics(generatedOtelMetrics ...pmetric.Metrics) pmetric.Me } return finalOtelMetrics } + func generateDeltaMetricMetadata(adjustToDelta bool, metricName string, retainInitialValueForDelta bool) deltaMetricMetadata { return deltaMetricMetadata{ adjustToDelta: adjustToDelta, diff --git a/exporter/awsemfexporter/emf_exporter.go b/exporter/awsemfexporter/emf_exporter.go index f840900b32d2..34b9eaf76856 100644 --- a/exporter/awsemfexporter/emf_exporter.go +++ b/exporter/awsemfexporter/emf_exporter.go @@ -76,7 +76,6 @@ func newEmfExporter(config *Config, set exporter.Settings) (*emfExporter, error) cwlogs.WithUserAgentExtras(userAgentExtras...), ) collectorIdentifier, err := uuid.NewRandom() - if err != nil { return nil, err } diff --git a/exporter/awsemfexporter/metric_translator.go b/exporter/awsemfexporter/metric_translator.go index 4e6c1d0bf739..bb16a5ea3346 100644 --- a/exporter/awsemfexporter/metric_translator.go +++ b/exporter/awsemfexporter/metric_translator.go @@ -449,7 +449,6 @@ func translateCWMetricToEMF(cWMetric *cWMetrics, config *Config) (*cwlogs.Event, func translateGroupedMetricToEmf(groupedMetric *groupedMetric, config *Config, defaultLogStream string) (*cwlogs.Event, error) { cWMetric := translateGroupedMetricToCWMetric(groupedMetric, config) event, err := translateCWMetricToEMF(cWMetric, config) - if err != nil { return nil, err } diff --git a/exporter/awsemfexporter/metric_translator_test.go b/exporter/awsemfexporter/metric_translator_test.go index e86176fc1fa6..15c74767d7d8 100644 --- a/exporter/awsemfexporter/metric_translator_test.go +++ b/exporter/awsemfexporter/metric_translator_test.go @@ -431,7 +431,6 @@ func TestTranslateCWMetricToEMF(t *testing.T) { for name, tc := range testCases { t.Run(name, func(_ *testing.T) { config := &Config{ - // include valid json string, a non-existing key, and keys whose value are not json/string ParseJSONEncodedAttributeValues: []string{"kubernetes", "Sources", "NonExistingAttributeKey", "spanName", "spanCounter"}, Version: tc.emfVersion, @@ -1335,7 +1334,8 @@ func TestGroupedMetricToCWMeasurementsWithFilters(t *testing.T) { Dimensions: [][]string{{}}, MetricNameSelectors: []string{"metric(1|3)"}, }, - }, []cWMeasurement{ + }, + []cWMeasurement{ { Namespace: namespace, Dimensions: [][]string{{}}, @@ -2194,123 +2194,121 @@ type logGroupStreamTest struct { outLogStreamName string } -var ( - logGroupStreamTestCases = []logGroupStreamTest{ - { - name: "log_group_stream_expect_same", - inputMetrics: generateTestMetrics(testMetric{ - metricNames: []string{"metric_1", "metric_2"}, - metricValues: [][]float64{{100}, {4}}, - }), - inLogGroupName: "test-log-group", - inLogStreamName: "test-log-stream", - outLogGroupName: "test-log-group", - outLogStreamName: "test-log-stream", - }, - { - name: "log_group_pattern_from_resource", - inputMetrics: generateTestMetrics(testMetric{ - metricNames: []string{"metric_1", "metric_2"}, - metricValues: [][]float64{{100}, {4}}, - resourceAttributeMap: map[string]any{ - "ClusterName": "test-cluster", - "PodName": "test-pod", - }, - }), - inLogGroupName: "test-log-group-{ClusterName}", - inLogStreamName: "test-log-stream", - outLogGroupName: "test-log-group-test-cluster", - outLogStreamName: "test-log-stream", - }, - { - name: "log_stream_pattern_from_resource", - inputMetrics: generateTestMetrics(testMetric{ - metricNames: []string{"metric_1", "metric_2"}, - metricValues: [][]float64{{100}, {4}}, - resourceAttributeMap: map[string]any{ - "ClusterName": "test-cluster", - "PodName": "test-pod", - }, - }), - inLogGroupName: "test-log-group", - inLogStreamName: "test-log-stream-{PodName}", - outLogGroupName: "test-log-group", - outLogStreamName: "test-log-stream-test-pod", - }, - { - name: "log_group_pattern_from_label", - inputMetrics: generateTestMetrics(testMetric{ - metricNames: []string{"metric_1", "metric_2"}, - metricValues: [][]float64{{100}, {4}}, - attributeMap: map[string]any{ - "ClusterName": "test-cluster", - "PodName": "test-pod", - }, - }), - inLogGroupName: "test-log-group-{ClusterName}", - inLogStreamName: "test-log-stream", - outLogGroupName: "test-log-group-test-cluster", - outLogStreamName: "test-log-stream", - }, - { - name: "log_stream_pattern_from_label", - inputMetrics: generateTestMetrics(testMetric{ - metricNames: []string{"metric_1", "metric_2"}, - metricValues: [][]float64{{100}, {4}}, - attributeMap: map[string]any{ - "ClusterName": "test-cluster", - "PodName": "test-pod", - }, - }), - inLogGroupName: "test-log-group", - inLogStreamName: "test-log-stream-{PodName}", - outLogGroupName: "test-log-group", - outLogStreamName: "test-log-stream-test-pod", - }, - { - name: "config_pattern_from_both_attributes", - inputMetrics: generateTestMetrics(testMetric{ - metricNames: []string{"metric_1", "metric_2"}, - metricValues: [][]float64{{100}, {4}}, - resourceAttributeMap: map[string]any{ - "ClusterName": "test-cluster", - }, - attributeMap: map[string]any{ - "PodName": "test-pod", - }, - }), - inLogGroupName: "test-log-group-{ClusterName}", - inLogStreamName: "test-log-stream-{PodName}", - outLogGroupName: "test-log-group-test-cluster", - outLogStreamName: "test-log-stream-test-pod", - }, - { - name: "config_pattern_missing_from_both_attributes", - inputMetrics: generateTestMetrics(testMetric{ - metricNames: []string{"metric_1", "metric_2"}, - metricValues: [][]float64{{100}, {4}}, - }), - inLogGroupName: "test-log-group-{ClusterName}", - inLogStreamName: "test-log-stream-{PodName}", - outLogGroupName: "test-log-group-undefined", - outLogStreamName: "test-log-stream-undefined", - }, - { - name: "config_pattern_group_missing_stream_present", - inputMetrics: generateTestMetrics(testMetric{ - metricNames: []string{"metric_1", "metric_2"}, - metricValues: [][]float64{{100}, {4}}, - attributeMap: map[string]any{ - "PodName": "test-pod", - }, - }), - inLogGroupName: "test-log-group-{ClusterName}", - inLogStreamName: "test-log-stream-{PodName}", - outLogGroupName: "test-log-group-undefined", - outLogStreamName: "test-log-stream-test-pod", - }, - } -) +var logGroupStreamTestCases = []logGroupStreamTest{ + { + name: "log_group_stream_expect_same", + inputMetrics: generateTestMetrics(testMetric{ + metricNames: []string{"metric_1", "metric_2"}, + metricValues: [][]float64{{100}, {4}}, + }), + inLogGroupName: "test-log-group", + inLogStreamName: "test-log-stream", + outLogGroupName: "test-log-group", + outLogStreamName: "test-log-stream", + }, + { + name: "log_group_pattern_from_resource", + inputMetrics: generateTestMetrics(testMetric{ + metricNames: []string{"metric_1", "metric_2"}, + metricValues: [][]float64{{100}, {4}}, + resourceAttributeMap: map[string]any{ + "ClusterName": "test-cluster", + "PodName": "test-pod", + }, + }), + inLogGroupName: "test-log-group-{ClusterName}", + inLogStreamName: "test-log-stream", + outLogGroupName: "test-log-group-test-cluster", + outLogStreamName: "test-log-stream", + }, + { + name: "log_stream_pattern_from_resource", + inputMetrics: generateTestMetrics(testMetric{ + metricNames: []string{"metric_1", "metric_2"}, + metricValues: [][]float64{{100}, {4}}, + resourceAttributeMap: map[string]any{ + "ClusterName": "test-cluster", + "PodName": "test-pod", + }, + }), + inLogGroupName: "test-log-group", + inLogStreamName: "test-log-stream-{PodName}", + outLogGroupName: "test-log-group", + outLogStreamName: "test-log-stream-test-pod", + }, + { + name: "log_group_pattern_from_label", + inputMetrics: generateTestMetrics(testMetric{ + metricNames: []string{"metric_1", "metric_2"}, + metricValues: [][]float64{{100}, {4}}, + attributeMap: map[string]any{ + "ClusterName": "test-cluster", + "PodName": "test-pod", + }, + }), + inLogGroupName: "test-log-group-{ClusterName}", + inLogStreamName: "test-log-stream", + outLogGroupName: "test-log-group-test-cluster", + outLogStreamName: "test-log-stream", + }, + { + name: "log_stream_pattern_from_label", + inputMetrics: generateTestMetrics(testMetric{ + metricNames: []string{"metric_1", "metric_2"}, + metricValues: [][]float64{{100}, {4}}, + attributeMap: map[string]any{ + "ClusterName": "test-cluster", + "PodName": "test-pod", + }, + }), + inLogGroupName: "test-log-group", + inLogStreamName: "test-log-stream-{PodName}", + outLogGroupName: "test-log-group", + outLogStreamName: "test-log-stream-test-pod", + }, + { + name: "config_pattern_from_both_attributes", + inputMetrics: generateTestMetrics(testMetric{ + metricNames: []string{"metric_1", "metric_2"}, + metricValues: [][]float64{{100}, {4}}, + resourceAttributeMap: map[string]any{ + "ClusterName": "test-cluster", + }, + attributeMap: map[string]any{ + "PodName": "test-pod", + }, + }), + inLogGroupName: "test-log-group-{ClusterName}", + inLogStreamName: "test-log-stream-{PodName}", + outLogGroupName: "test-log-group-test-cluster", + outLogStreamName: "test-log-stream-test-pod", + }, + { + name: "config_pattern_missing_from_both_attributes", + inputMetrics: generateTestMetrics(testMetric{ + metricNames: []string{"metric_1", "metric_2"}, + metricValues: [][]float64{{100}, {4}}, + }), + inLogGroupName: "test-log-group-{ClusterName}", + inLogStreamName: "test-log-stream-{PodName}", + outLogGroupName: "test-log-group-undefined", + outLogStreamName: "test-log-stream-undefined", + }, + { + name: "config_pattern_group_missing_stream_present", + inputMetrics: generateTestMetrics(testMetric{ + metricNames: []string{"metric_1", "metric_2"}, + metricValues: [][]float64{{100}, {4}}, + attributeMap: map[string]any{ + "PodName": "test-pod", + }, + }), + inLogGroupName: "test-log-group-{ClusterName}", + inLogStreamName: "test-log-stream-{PodName}", + outLogGroupName: "test-log-group-undefined", + outLogStreamName: "test-log-stream-test-pod", + }, +} func TestTranslateOtToGroupedMetricForLogGroupAndStream(t *testing.T) { for _, test := range logGroupStreamTestCases { diff --git a/exporter/awskinesisexporter/exporter.go b/exporter/awskinesisexporter/exporter.go index acf83d831176..762afb09fa57 100644 --- a/exporter/awskinesisexporter/exporter.go +++ b/exporter/awskinesisexporter/exporter.go @@ -95,7 +95,6 @@ func createExporter(ctx context.Context, c component.Config, log *zap.Logger, op batch.WithMaxRecordsPerBatch(conf.MaxRecordsPerBatch), batch.WithCompressionType(conf.Compression), ) - if err != nil { return nil, err } diff --git a/exporter/awskinesisexporter/internal/compress/compresser.go b/exporter/awskinesisexporter/internal/compress/compresser.go index fe12413f1f1f..f0de7a766d13 100644 --- a/exporter/awskinesisexporter/internal/compress/compresser.go +++ b/exporter/awskinesisexporter/internal/compress/compresser.go @@ -33,7 +33,6 @@ func flateCompressor(in []byte) ([]byte, error) { w, _ := flate.NewWriter(&buf, flate.BestSpeed) _, err := w.Write(in) - if err != nil { return nil, err } @@ -56,7 +55,6 @@ func gzipCompressor(in []byte) ([]byte, error) { w, _ := gzip.NewWriterLevel(&buf, gzip.BestSpeed) _, err := w.Write(in) - if err != nil { return nil, err } @@ -79,7 +77,6 @@ func zlibCompressor(in []byte) ([]byte, error) { w, _ := zlib.NewWriterLevel(&buf, zlib.BestSpeed) _, err := w.Write(in) - if err != nil { return nil, err } diff --git a/exporter/awskinesisexporter/internal/compress/compresser_test.go b/exporter/awskinesisexporter/internal/compress/compresser_test.go index 44952fb2fb80..082427bb6133 100644 --- a/exporter/awskinesisexporter/internal/compress/compresser_test.go +++ b/exporter/awskinesisexporter/internal/compress/compresser_test.go @@ -172,7 +172,6 @@ func concurrentCompressFunc(t *testing.T) { // any single format would do it here, since each exporter can be set to use only one at a time // and the concurrent issue that was present in the past was independent of the format compressFunc, err := compress.NewCompressor("gzip") - if err != nil { errCh <- err return diff --git a/exporter/awskinesisexporter/internal/producer/batcher.go b/exporter/awskinesisexporter/internal/producer/batcher.go index 2b68e725608b..8e18dc933284 100644 --- a/exporter/awskinesisexporter/internal/producer/batcher.go +++ b/exporter/awskinesisexporter/internal/producer/batcher.go @@ -23,9 +23,7 @@ type batcher struct { log *zap.Logger } -var ( - _ Batcher = (*batcher)(nil) -) +var _ Batcher = (*batcher)(nil) var ( permanentErrResourceNotFound = new(*types.ResourceNotFoundException) @@ -52,7 +50,6 @@ func (b *batcher) Put(ctx context.Context, bt *batch.Batch) error { StreamName: b.stream, Records: records, }) - if err != nil { if errors.As(err, permanentErrResourceNotFound) || errors.As(err, permanentErrInvalidArgument) { err = consumererror.NewPermanent(err) diff --git a/exporter/awskinesisexporter/internal/producer/interface.go b/exporter/awskinesisexporter/internal/producer/interface.go index 0726e7f71cbb..3a3b40f20318 100644 --- a/exporter/awskinesisexporter/internal/producer/interface.go +++ b/exporter/awskinesisexporter/internal/producer/interface.go @@ -29,6 +29,4 @@ type Kinesis interface { PutRecords(ctx context.Context, params *kinesis.PutRecordsInput, optFns ...func(*kinesis.Options)) (*kinesis.PutRecordsOutput, error) } -var ( - _ Kinesis = (*kinesis.Client)(nil) -) +var _ Kinesis = (*kinesis.Client)(nil) diff --git a/exporter/awss3exporter/body_marshaler_test.go b/exporter/awss3exporter/body_marshaler_test.go index 0363e20722a2..0c4846a14b14 100644 --- a/exporter/awss3exporter/body_marshaler_test.go +++ b/exporter/awss3exporter/body_marshaler_test.go @@ -71,7 +71,7 @@ func TestBodyMarshalerWithMapType(t *testing.T) { m.PutDouble("foobardouble", 0.006) m.PutInt("foobarint", 1) - var expect = `{"bar":"bar","foo":"foo","foobar":false,"foobardouble":0.006,"foobarint":1}` + expect := `{"bar":"bar","foo":"foo","foobar":false,"foobardouble":0.006,"foobarint":1}` marshaler := &bodyMarshaler{} require.NotNil(t, marshaler) diff --git a/exporter/awss3exporter/exporter.go b/exporter/awss3exporter/exporter.go index 3a89cf00ee32..b3e84aaa7af8 100644 --- a/exporter/awss3exporter/exporter.go +++ b/exporter/awss3exporter/exporter.go @@ -24,7 +24,8 @@ type s3Exporter struct { } func newS3Exporter(config *Config, - params exporter.Settings) *s3Exporter { + params exporter.Settings, +) *s3Exporter { s3Exporter := &s3Exporter{ config: config, dataWriter: &s3Writer{}, @@ -56,7 +57,6 @@ func (e *s3Exporter) Capabilities() consumer.Capabilities { func (e *s3Exporter) ConsumeMetrics(ctx context.Context, md pmetric.Metrics) error { buf, err := e.marshaler.MarshalMetrics(md) - if err != nil { return err } @@ -66,7 +66,6 @@ func (e *s3Exporter) ConsumeMetrics(ctx context.Context, md pmetric.Metrics) err func (e *s3Exporter) ConsumeLogs(ctx context.Context, logs plog.Logs) error { buf, err := e.marshaler.MarshalLogs(logs) - if err != nil { return err } diff --git a/exporter/awss3exporter/factory.go b/exporter/awss3exporter/factory.go index ee4d3eae72fe..75964280fca7 100644 --- a/exporter/awss3exporter/factory.go +++ b/exporter/awss3exporter/factory.go @@ -37,7 +37,8 @@ func createDefaultConfig() component.Config { func createLogsExporter(ctx context.Context, params exporter.Settings, - config component.Config) (exporter.Logs, error) { + config component.Config, +) (exporter.Logs, error) { s3Exporter := newS3Exporter(config.(*Config), params) return exporterhelper.NewLogs(ctx, params, @@ -48,7 +49,8 @@ func createLogsExporter(ctx context.Context, func createMetricsExporter(ctx context.Context, params exporter.Settings, - config component.Config) (exporter.Metrics, error) { + config component.Config, +) (exporter.Metrics, error) { s3Exporter := newS3Exporter(config.(*Config), params) if config.(*Config).MarshalerName == SumoIC { @@ -63,7 +65,8 @@ func createMetricsExporter(ctx context.Context, func createTracesExporter(ctx context.Context, params exporter.Settings, - config component.Config) (exporter.Traces, error) { + config component.Config, +) (exporter.Traces, error) { s3Exporter := newS3Exporter(config.(*Config), params) if config.(*Config).MarshalerName == SumoIC { diff --git a/exporter/awss3exporter/marshaler.go b/exporter/awss3exporter/marshaler.go index 57ac6455d823..006cdf45c526 100644 --- a/exporter/awss3exporter/marshaler.go +++ b/exporter/awss3exporter/marshaler.go @@ -21,9 +21,7 @@ type marshaler interface { format() string } -var ( - ErrUnknownMarshaler = errors.New("unknown marshaler") -) +var ErrUnknownMarshaler = errors.New("unknown marshaler") func newMarshalerFromEncoding(encoding *component.ID, fileFormat string, host component.Host, logger *zap.Logger) (marshaler, error) { marshaler := &s3Marshaler{logger: logger} diff --git a/exporter/awss3exporter/marshaler_test.go b/exporter/awss3exporter/marshaler_test.go index 0f651fa87cc3..c6aaefe51806 100644 --- a/exporter/awss3exporter/marshaler_test.go +++ b/exporter/awss3exporter/marshaler_test.go @@ -56,8 +56,7 @@ func (h hostWithExtensions) GetExtensions() map[component.ID]component.Component } } -type encodingExtension struct { -} +type encodingExtension struct{} func (e encodingExtension) Start(_ context.Context, _ component.Host) error { panic("unsupported") diff --git a/exporter/awss3exporter/s3_writer.go b/exporter/awss3exporter/s3_writer.go index 38376c45605d..13667f38a074 100644 --- a/exporter/awss3exporter/s3_writer.go +++ b/exporter/awss3exporter/s3_writer.go @@ -19,8 +19,7 @@ import ( "go.opentelemetry.io/collector/config/configcompression" ) -type s3Writer struct { -} +type s3Writer struct{} // generate the s3 time key based on partition configuration func getTimeKey(time time.Time, partition string) string { @@ -113,7 +112,6 @@ func (s3writer *s3Writer) writeBuffer(_ context.Context, buf []byte, config *Con sessionConfig := getSessionConfig(config) sess, err := getSession(config, sessionConfig) - if err != nil { return err } diff --git a/exporter/awsxrayexporter/internal/translator/aws.go b/exporter/awsxrayexporter/internal/translator/aws.go index d1db1c57d17f..20002ce3fc0d 100644 --- a/exporter/awsxrayexporter/internal/translator/aws.go +++ b/exporter/awsxrayexporter/internal/translator/aws.go @@ -230,7 +230,7 @@ func makeAws(attributes map[string]pcommon.Value, resource pcommon.Resource, log case logGroups != (pcommon.Slice{}) && logGroups.Len() > 0: cwl = getLogGroupMetadata(logGroups, false) case logGroupNames != nil: - var configSlice = pcommon.NewSlice() + configSlice := pcommon.NewSlice() configSlice.EnsureCapacity(len(logGroupNames)) for _, s := range logGroupNames { diff --git a/exporter/awsxrayexporter/internal/translator/cause.go b/exporter/awsxrayexporter/internal/translator/cause.go index b5a3fd3b85a4..35acc84d4064 100644 --- a/exporter/awsxrayexporter/internal/translator/cause.go +++ b/exporter/awsxrayexporter/internal/translator/cause.go @@ -21,14 +21,17 @@ import ( // ExceptionEventName the name of the exception event. // TODO: Remove this when collector defines this semantic convention. -const ExceptionEventName = "exception" -const AwsIndividualHTTPEventName = "HTTP request failure" -const AwsIndividualHTTPErrorEventType = "aws.http.error.event" -const AwsIndividualHTTPErrorCodeAttr = "http.response.status_code" -const AwsIndividualHTTPErrorMsgAttr = "aws.http.error_message" +const ( + ExceptionEventName = "exception" + AwsIndividualHTTPEventName = "HTTP request failure" + AwsIndividualHTTPErrorEventType = "aws.http.error.event" + AwsIndividualHTTPErrorCodeAttr = "http.response.status_code" + AwsIndividualHTTPErrorMsgAttr = "aws.http.error_message" +) func makeCause(span ptrace.Span, attributes map[string]pcommon.Value, resource pcommon.Resource) (isError, isFault, isThrottle bool, - filtered map[string]pcommon.Value, cause *awsxray.CauseData) { + filtered map[string]pcommon.Value, cause *awsxray.CauseData, +) { status := span.Status() filtered = attributes @@ -112,7 +115,9 @@ func makeCause(span ptrace.Span, attributes map[string]pcommon.Value, resource p cause = &awsxray.CauseData{ Type: awsxray.CauseTypeObject, CauseObject: awsxray.CauseObject{ - Exceptions: exceptions}} + Exceptions: exceptions, + }, + } case status.Code() != ptrace.StatusCodeError: cause = nil diff --git a/exporter/awsxrayexporter/internal/translator/cause_test.go b/exporter/awsxrayexporter/internal/translator/cause_test.go index 48b56aaa33a8..65759105dcaa 100644 --- a/exporter/awsxrayexporter/internal/translator/cause_test.go +++ b/exporter/awsxrayexporter/internal/translator/cause_test.go @@ -94,7 +94,7 @@ func TestMakeCauseAwsSdkSpan(t *testing.T) { } func TestCauseExceptionWithoutError(t *testing.T) { - var nonErrorStatusCodes = []ptrace.StatusCode{ptrace.StatusCodeUnset, ptrace.StatusCodeOk} + nonErrorStatusCodes := []ptrace.StatusCode{ptrace.StatusCodeUnset, ptrace.StatusCodeOk} for _, element := range nonErrorStatusCodes { ExceptionWithoutErrorHelper(t, element) @@ -104,7 +104,7 @@ func TestCauseExceptionWithoutError(t *testing.T) { func ExceptionWithoutErrorHelper(t *testing.T, statusCode ptrace.StatusCode) { errorMsg := "this is a test" - var exceptionStack = `java.lang.IllegalStateException: state is not legal + exceptionStack := `java.lang.IllegalStateException: state is not legal at io.opentelemetry.sdk.trace.RecordEventsReadableSpanTest.recordException(RecordEventsReadableSpanTest.java:626) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) @@ -140,7 +140,7 @@ Caused by: java.lang.IllegalArgumentException: bad argument` } func TestEventWithoutExceptionWithoutError(t *testing.T) { - var nonErrorStatusCodes = []ptrace.StatusCode{ptrace.StatusCodeUnset, ptrace.StatusCodeOk} + nonErrorStatusCodes := []ptrace.StatusCode{ptrace.StatusCodeUnset, ptrace.StatusCodeOk} for _, element := range nonErrorStatusCodes { EventWithoutExceptionWithoutErrorHelper(t, element) diff --git a/exporter/awsxrayexporter/internal/translator/http_test.go b/exporter/awsxrayexporter/internal/translator/http_test.go index 82f678c54171..92fb6b50bc30 100644 --- a/exporter/awsxrayexporter/internal/translator/http_test.go +++ b/exporter/awsxrayexporter/internal/translator/http_test.go @@ -458,6 +458,7 @@ func TestSpanWithClientAddrWithoutNetworkPeerAddr(t *testing.T) { assert.Equal(t, aws.Bool(true), httpData.Request.XForwardedFor) } + func TestSpanWithClientAddrAndNetworkPeerAddr(t *testing.T) { attributes := make(map[string]any) attributes[AttributeURLFull] = "https://api.example.com/users/junit" diff --git a/exporter/awsxrayexporter/internal/translator/segment.go b/exporter/awsxrayexporter/internal/translator/segment.go index 98f6211cd1fd..849416bcd2ef 100644 --- a/exporter/awsxrayexporter/internal/translator/segment.go +++ b/exporter/awsxrayexporter/internal/translator/segment.go @@ -46,21 +46,17 @@ const ( k8sRemoteNamespace = "K8s.RemoteNamespace" ) -var ( - // reInvalidSpanCharacters defines the invalid letters in a span name as per - // Allowed characters for X-Ray Segment Name: - // Unicode letters, numbers, and whitespace, and the following symbols: _, ., :, /, %, &, #, =, +, \, -, @ - // Doc: https://docs.aws.amazon.com/xray/latest/devguide/xray-api-segmentdocuments.html - reInvalidSpanCharacters = regexp.MustCompile(`[^ 0-9\p{L}N_.:/%&#=+\-@]`) -) - -var ( - remoteXrayExporterDotConverter = featuregate.GlobalRegistry().MustRegister( - "exporter.xray.allowDot", - featuregate.StageBeta, - featuregate.WithRegisterDescription("X-Ray Exporter will no longer convert . to _ in annotation keys when this feature gate is enabled. "), - featuregate.WithRegisterFromVersion("v0.97.0"), - ) +// reInvalidSpanCharacters defines the invalid letters in a span name as per +// Allowed characters for X-Ray Segment Name: +// Unicode letters, numbers, and whitespace, and the following symbols: _, ., :, /, %, &, #, =, +, \, -, @ +// Doc: https://docs.aws.amazon.com/xray/latest/devguide/xray-api-segmentdocuments.html +var reInvalidSpanCharacters = regexp.MustCompile(`[^ 0-9\p{L}N_.:/%&#=+\-@]`) + +var remoteXrayExporterDotConverter = featuregate.GlobalRegistry().MustRegister( + "exporter.xray.allowDot", + featuregate.StageBeta, + featuregate.WithRegisterDescription("X-Ray Exporter will no longer convert . to _ in annotation keys when this feature gate is enabled. "), + featuregate.WithRegisterFromVersion("v0.97.0"), ) const ( @@ -90,9 +86,7 @@ var removeAnnotationsFromServiceSegment = []string{ k8sRemoteNamespace, } -var ( - writers = newWriterPool(2048) -) +var writers = newWriterPool(2048) // MakeSegmentDocuments converts spans to json documents func MakeSegmentDocuments(span ptrace.Span, resource pcommon.Resource, indexedAttrs []string, indexAllAttrs bool, logGroupNames []string, skipTimestampValidation bool) ([]string, error) { @@ -143,13 +137,12 @@ func addNamespaceToSubsegmentWithRemoteService(span ptrace.Span, segment *awsxra } func MakeDependencySubsegmentForLocalRootDependencySpan(span ptrace.Span, resource pcommon.Resource, indexedAttrs []string, indexAllAttrs bool, logGroupNames []string, skipTimestampValidation bool, serviceSegmentID pcommon.SpanID) (*awsxray.Segment, error) { - var dependencySpan = ptrace.NewSpan() + dependencySpan := ptrace.NewSpan() span.CopyTo(dependencySpan) dependencySpan.SetParentSpanID(serviceSegmentID) dependencySubsegment, err := MakeSegment(dependencySpan, resource, indexedAttrs, indexAllAttrs, logGroupNames, skipTimestampValidation) - if err != nil { return nil, err } @@ -187,7 +180,6 @@ func MakeServiceSegmentForLocalRootDependencySpan(span ptrace.Span, resource pco } serviceSegment, err := MakeSegment(serviceSpan, resource, indexedAttrs, indexAllAttrs, logGroupNames, skipTimestampValidation) - if err != nil { return nil, err } @@ -234,7 +226,6 @@ func MakeServiceSegmentForLocalRootDependencySpan(span ptrace.Span, resource pco func MakeServiceSegmentForLocalRootSpanWithoutDependency(span ptrace.Span, resource pcommon.Resource, indexedAttrs []string, indexAllAttrs bool, logGroupNames []string, skipTimestampValidation bool) ([]*awsxray.Segment, error) { segment, err := MakeSegment(span, resource, indexedAttrs, indexAllAttrs, logGroupNames, skipTimestampValidation) - if err != nil { return nil, err } @@ -247,7 +238,6 @@ func MakeServiceSegmentForLocalRootSpanWithoutDependency(span ptrace.Span, resou func MakeNonLocalRootSegment(span ptrace.Span, resource pcommon.Resource, indexedAttrs []string, indexAllAttrs bool, logGroupNames []string, skipTimestampValidation bool) ([]*awsxray.Segment, error) { segment, err := MakeSegment(span, resource, indexedAttrs, indexAllAttrs, logGroupNames, skipTimestampValidation) - if err != nil { return nil, err } @@ -259,7 +249,7 @@ func MakeNonLocalRootSegment(span ptrace.Span, resource pcommon.Resource, indexe func MakeServiceSegmentAndDependencySubsegment(span ptrace.Span, resource pcommon.Resource, indexedAttrs []string, indexAllAttrs bool, logGroupNames []string, skipTimestampValidation bool) ([]*awsxray.Segment, error) { // If it is a local root span and a dependency span, we need to make a segment and subsegment representing the local service and remote service, respectively. - var serviceSegmentID = newSegmentID() + serviceSegmentID := newSegmentID() var segments []*awsxray.Segment // Make Dependency Subsegment @@ -296,7 +286,6 @@ func MakeSegmentsFromSpan(span ptrace.Span, resource pcommon.Resource, indexedAt // MakeSegmentDocumentString will be deprecated in the future func MakeSegmentDocumentString(span ptrace.Span, resource pcommon.Resource, indexedAttrs []string, indexAllAttrs bool, logGroupNames []string, skipTimestampValidation bool) (string, error) { segment, err := MakeSegment(span, resource, indexedAttrs, indexAllAttrs, logGroupNames, skipTimestampValidation) - if err != nil { return "", err } @@ -612,7 +601,8 @@ func addSpecialAttributes(attributes map[string]pcommon.Value, indexedAttrs []st } func makeXRayAttributes(attributes map[string]pcommon.Value, resource pcommon.Resource, storeResource bool, indexedAttrs []string, indexAllAttrs bool) ( - string, map[string]any, map[string]map[string]any) { + string, map[string]any, map[string]map[string]any, +) { var ( annotations = map[string]any{} metadata = map[string]map[string]any{} diff --git a/exporter/awsxrayexporter/internal/translator/segment_test.go b/exporter/awsxrayexporter/internal/translator/segment_test.go index 39e17fd972ef..1b057c9ad899 100644 --- a/exporter/awsxrayexporter/internal/translator/segment_test.go +++ b/exporter/awsxrayexporter/internal/translator/segment_test.go @@ -30,9 +30,7 @@ const ( resourceArrayKey = "array.key" ) -var ( - testWriters = newWriterPool(2048) -) +var testWriters = newWriterPool(2048) func TestClientSpanWithRpcAwsSdkClientAttributes(t *testing.T) { spanName := "AmazonDynamoDB.getItem" @@ -1544,7 +1542,7 @@ func validateLocalRootWithoutDependency(t *testing.T, segment *awsxray.Segment, assert.Equal(t, "myRemoteService", segment.Annotations["aws_remote_service"]) assert.Equal(t, "myAnnotationValue", segment.Annotations["myAnnotationKey"]) - var numberOfMetadataKeys = 8 + numberOfMetadataKeys := 8 if span.Kind() == ptrace.SpanKindServer { numberOfMetadataKeys = 30 diff --git a/exporter/awsxrayexporter/internal/translator/span_links.go b/exporter/awsxrayexporter/internal/translator/span_links.go index 7a262b2fa5b1..c7b3df473423 100644 --- a/exporter/awsxrayexporter/internal/translator/span_links.go +++ b/exporter/awsxrayexporter/internal/translator/span_links.go @@ -15,11 +15,10 @@ func makeSpanLinks(links ptrace.SpanLinkSlice, skipTimestampValidation bool) ([] for i := 0; i < links.Len(); i++ { var spanLinkData awsxray.SpanLinkData - var link = links.At(i) + link := links.At(i) - var spanID = link.SpanID().String() + spanID := link.SpanID().String() traceID, err := convertToAmazonTraceID(link.TraceID(), skipTimestampValidation) - if err != nil { return nil, err } diff --git a/exporter/awsxrayexporter/internal/translator/span_links_test.go b/exporter/awsxrayexporter/internal/translator/span_links_test.go index 6c1fb6107bf8..5347c8c15525 100644 --- a/exporter/awsxrayexporter/internal/translator/span_links_test.go +++ b/exporter/awsxrayexporter/internal/translator/span_links_test.go @@ -19,7 +19,7 @@ func TestSpanLinkSimple(t *testing.T) { resource := constructDefaultResource() span := constructServerSpan(parentSpanID, spanName, ptrace.StatusCodeOk, "OK", attributes) - var traceID = newTraceID() + traceID := newTraceID() spanLink := span.Links().AppendEmpty() spanLink.SetTraceID(traceID) @@ -27,7 +27,7 @@ func TestSpanLinkSimple(t *testing.T) { segment, _ := MakeSegment(span, resource, nil, false, nil, false) - var convertedTraceID, _ = convertToAmazonTraceID(traceID, false) + convertedTraceID, _ := convertToAmazonTraceID(traceID, false) assert.Len(t, segment.Links, 1) assert.Equal(t, spanLink.SpanID().String(), *segment.Links[0].SpanID) @@ -68,7 +68,7 @@ func TestOldSpanLinkError(t *testing.T) { const maxAge = 60 * 60 * 24 * 30 ExpiredEpoch := time.Now().Unix() - maxAge - 1 - var traceID = newTraceID() + traceID := newTraceID() binary.BigEndian.PutUint32(traceID[0:4], uint32(ExpiredEpoch)) spanLink := span.Links().AppendEmpty() @@ -91,14 +91,14 @@ func TestTwoSpanLinks(t *testing.T) { resource := constructDefaultResource() span := constructServerSpan(parentSpanID, spanName, ptrace.StatusCodeOk, "OK", attributes) - var traceID1 = newTraceID() + traceID1 := newTraceID() spanLink1 := span.Links().AppendEmpty() spanLink1.SetTraceID(traceID1) spanLink1.SetSpanID(newSegmentID()) spanLink1.Attributes().PutStr("myKey1", "ABC") - var traceID2 = newTraceID() + traceID2 := newTraceID() spanLink2 := span.Links().AppendEmpty() spanLink2.SetTraceID(traceID2) @@ -107,8 +107,8 @@ func TestTwoSpanLinks(t *testing.T) { segment, _ := MakeSegment(span, resource, nil, false, nil, false) - var convertedTraceID1, _ = convertToAmazonTraceID(traceID1, false) - var convertedTraceID2, _ = convertToAmazonTraceID(traceID2, false) + convertedTraceID1, _ := convertToAmazonTraceID(traceID1, false) + convertedTraceID2, _ := convertToAmazonTraceID(traceID2, false) assert.Len(t, segment.Links, 2) assert.Equal(t, spanLink1.SpanID().String(), *segment.Links[0].SpanID) @@ -149,23 +149,23 @@ func TestSpanLinkComplexAttributes(t *testing.T) { spanLink.Attributes().PutInt("myKey3", 112233) spanLink.Attributes().PutDouble("myKey4", 3.1415) - var slice1 = spanLink.Attributes().PutEmptySlice("myKey5") + slice1 := spanLink.Attributes().PutEmptySlice("myKey5") slice1.AppendEmpty().SetStr("apple") slice1.AppendEmpty().SetStr("pear") slice1.AppendEmpty().SetStr("banana") - var slice2 = spanLink.Attributes().PutEmptySlice("myKey6") + slice2 := spanLink.Attributes().PutEmptySlice("myKey6") slice2.AppendEmpty().SetBool(true) slice2.AppendEmpty().SetBool(false) slice2.AppendEmpty().SetBool(false) slice2.AppendEmpty().SetBool(true) - var slice3 = spanLink.Attributes().PutEmptySlice("myKey7") + slice3 := spanLink.Attributes().PutEmptySlice("myKey7") slice3.AppendEmpty().SetInt(1234) slice3.AppendEmpty().SetInt(5678) slice3.AppendEmpty().SetInt(9012) - var slice4 = spanLink.Attributes().PutEmptySlice("myKey8") + slice4 := spanLink.Attributes().PutEmptySlice("myKey8") slice4.AppendEmpty().SetDouble(2.718) slice4.AppendEmpty().SetDouble(1.618) diff --git a/exporter/azuredataexplorerexporter/adx_exporter.go b/exporter/azuredataexplorerexporter/adx_exporter.go index 967c944836fa..b1b76b34e056 100644 --- a/exporter/azuredataexplorerexporter/adx_exporter.go +++ b/exporter/azuredataexplorerexporter/adx_exporter.go @@ -150,7 +150,6 @@ func newExporter(config *Config, logger *zap.Logger, telemetryDataType int, vers return nil, err } metricClient, err := buildAdxClient(config, version) - if err != nil { return nil, err } diff --git a/exporter/azuredataexplorerexporter/adx_exporter_test.go b/exporter/azuredataexplorerexporter/adx_exporter_test.go index 269aabb6d493..7bd1313347fb 100644 --- a/exporter/azuredataexplorerexporter/adx_exporter_test.go +++ b/exporter/azuredataexplorerexporter/adx_exporter_test.go @@ -25,7 +25,8 @@ import ( func TestNewExporter(t *testing.T) { logger := zaptest.NewLogger(t) - c := Config{ClusterURI: "https://CLUSTER.kusto.windows.net", + c := Config{ + ClusterURI: "https://CLUSTER.kusto.windows.net", ApplicationID: "unknown", ApplicationKey: "unknown", TenantID: "unknown", diff --git a/exporter/azuredataexplorerexporter/factory.go b/exporter/azuredataexplorerexporter/factory.go index 886f9336f3a2..4e45ff99c941 100644 --- a/exporter/azuredataexplorerexporter/factory.go +++ b/exporter/azuredataexplorerexporter/factory.go @@ -64,7 +64,6 @@ func createMetricsExporter( // call the common exporter function in baseexporter. This ensures that the client and the ingest // are initialized and the metrics struct are available for operations adp, err := newExporter(adxCfg, set.Logger, metricsType, version) - if err != nil { return nil, err } @@ -78,7 +77,6 @@ func createMetricsExporter( exporterhelper.WithRetry(adxCfg.BackOffConfig), exporterhelper.WithQueue(adxCfg.QueueSettings), exporterhelper.WithShutdown(adp.Close)) - if err != nil { return nil, err } @@ -96,7 +94,6 @@ func createTracesExporter( // call the common exporter function in baseexporter. This ensures that the client and the ingest // are initialized and the metrics struct are available for operations adp, err := newExporter(adxCfg, set.Logger, tracesType, version) - if err != nil { return nil, err } @@ -110,7 +107,6 @@ func createTracesExporter( exporterhelper.WithRetry(adxCfg.BackOffConfig), exporterhelper.WithQueue(adxCfg.QueueSettings), exporterhelper.WithShutdown(adp.Close)) - if err != nil { return nil, err } @@ -128,7 +124,6 @@ func createLogsExporter( // call the common exporter function in baseexporter. This ensures that the client and the ingest // are initialized and the metrics struct are available for operations adp, err := newExporter(adxCfg, set.Logger, logsType, version) - if err != nil { return nil, err } @@ -142,7 +137,6 @@ func createLogsExporter( exporterhelper.WithRetry(adxCfg.BackOffConfig), exporterhelper.WithQueue(adxCfg.QueueSettings), exporterhelper.WithShutdown(adp.Close)) - if err != nil { return nil, err } diff --git a/exporter/azuredataexplorerexporter/metricsdata_to_adx.go b/exporter/azuredataexplorerexporter/metricsdata_to_adx.go index ff2398016ee3..a80fc1342d56 100644 --- a/exporter/azuredataexplorerexporter/metricsdata_to_adx.go +++ b/exporter/azuredataexplorerexporter/metricsdata_to_adx.go @@ -133,8 +133,7 @@ func mapToAdxMetric(res pcommon.Resource, md pmetric.Metric, scopeattrs map[stri value := uint64(0) // now create buckets for each bound. for bi := 0; bi < bounds.Len(); bi++ { - customMap := - copyMap(map[string]any{"le": float64ToDimValue(bounds.At(bi))}, dataPoint.Attributes().AsRaw()) + customMap := copyMap(map[string]any{"le": float64ToDimValue(bounds.At(bi))}, dataPoint.Attributes().AsRaw()) value += counts.At(bi) vMap := pcommon.NewMap() @@ -151,10 +150,9 @@ func mapToAdxMetric(res pcommon.Resource, md pmetric.Metric, scopeattrs map[stri // add an upper bound for +Inf { // Add the LE field for the bucket's bound - customMap := - copyMap(map[string]any{ - "le": float64ToDimValue(math.Inf(1)), - }, dataPoint.Attributes().AsRaw()) + customMap := copyMap(map[string]any{ + "le": float64ToDimValue(math.Inf(1)), + }, dataPoint.Attributes().AsRaw()) vMap := pcommon.NewMap() //nolint:errcheck vMap.FromRaw(customMap) diff --git a/exporter/azuredataexplorerexporter/metricsdata_to_adx_test.go b/exporter/azuredataexplorerexporter/metricsdata_to_adx_test.go index 9d0b10929936..99089b23f2d5 100644 --- a/exporter/azuredataexplorerexporter/metricsdata_to_adx_test.go +++ b/exporter/azuredataexplorerexporter/metricsdata_to_adx_test.go @@ -23,13 +23,17 @@ const ( ) // The timestamps used for the tests -var tsUnix = time.Unix(time.Now().Unix(), time.Now().UnixNano()) -var ts = pcommon.NewTimestampFromTime(tsUnix) -var tstr = ts.AsTime().Format(time.RFC3339Nano) +var ( + tsUnix = time.Unix(time.Now().Unix(), time.Now().UnixNano()) + ts = pcommon.NewTimestampFromTime(tsUnix) + tstr = ts.AsTime().Format(time.RFC3339Nano) +) // the histogram values and distribution for the tests -var distributionBounds = []float64{1, 2, 4} -var distributionCounts = []uint64{4, 2, 3, 5} +var ( + distributionBounds = []float64{1, 2, 4} + distributionCounts = []uint64{4, 2, 3, 5} +) func Test_rawMetricsToAdxMetrics(t *testing.T) { t.Parallel() diff --git a/exporter/azuredataexplorerexporter/tracesdata_to_adx_test.go b/exporter/azuredataexplorerexporter/tracesdata_to_adx_test.go index 55e6b2e67301..9a570c544eab 100644 --- a/exporter/azuredataexplorerexporter/tracesdata_to_adx_test.go +++ b/exporter/azuredataexplorerexporter/tracesdata_to_adx_test.go @@ -61,7 +61,8 @@ func Test_mapToAdxTrace(t *testing.T) { Events: getEmptyEvents(), Links: getEmptyLinks(), }, - }, { + }, + { name: "No data", spanDatafn: func() ptrace.Span { span := ptrace.NewSpan() @@ -79,7 +80,8 @@ func Test_mapToAdxTrace(t *testing.T) { Events: getEmptyEvents(), Links: getEmptyLinks(), }, - }, { + }, + { name: "with_events_links", spanDatafn: func() ptrace.Span { span := ptrace.NewSpan() diff --git a/exporter/azuremonitorexporter/config_test.go b/exporter/azuremonitorexporter/config_test.go index 48be4f03d159..d63c025a3d6c 100644 --- a/exporter/azuremonitorexporter/config_test.go +++ b/exporter/azuremonitorexporter/config_test.go @@ -29,7 +29,6 @@ func TestLoadConfig(t *testing.T) { id component.ID expected component.Config }{ - { id: component.NewIDWithName(metadata.Type, ""), expected: createDefaultConfig(), diff --git a/exporter/azuremonitorexporter/factory.go b/exporter/azuremonitorexporter/factory.go index 35364d934f53..39801b81f822 100644 --- a/exporter/azuremonitorexporter/factory.go +++ b/exporter/azuremonitorexporter/factory.go @@ -24,9 +24,7 @@ const ( defaultEndpoint = "https://dc.services.visualstudio.com/v2/track" ) -var ( - errUnexpectedConfigurationType = errors.New("failed to cast configuration to Azure Monitor Config") -) +var errUnexpectedConfigurationType = errors.New("failed to cast configuration to Azure Monitor Config") // NewFactory returns a factory for Azure Monitor exporter. func NewFactory() exporter.Factory { diff --git a/exporter/azuremonitorexporter/factory_test.go b/exporter/azuremonitorexporter/factory_test.go index 67c2cdf60250..c0875782bd14 100644 --- a/exporter/azuremonitorexporter/factory_test.go +++ b/exporter/azuremonitorexporter/factory_test.go @@ -12,8 +12,7 @@ import ( ) // An inappropriate config -type badConfig struct { -} +type badConfig struct{} func TestCreateTracesUsingSpecificTransportChannel(t *testing.T) { // mock transport channel creation diff --git a/exporter/azuremonitorexporter/time_utils_test.go b/exporter/azuremonitorexporter/time_utils_test.go index 1034ae9f17a3..78807c89a276 100644 --- a/exporter/azuremonitorexporter/time_utils_test.go +++ b/exporter/azuremonitorexporter/time_utils_test.go @@ -17,7 +17,7 @@ func TestToTime(t *testing.T) { output := toTime(input) assert.NotNil(t, output) - expected := time.Date(1970, 01, 01, 00, 01, 00, 1, time.UTC) + expected := time.Date(1970, 0o1, 0o1, 0o0, 0o1, 0o0, 1, time.UTC) assert.Equal(t, "1970-01-01T00:01:00.000000001Z", expected.Format(time.RFC3339Nano)) } diff --git a/exporter/azuremonitorexporter/trace_to_envelope.go b/exporter/azuremonitorexporter/trace_to_envelope.go index 219902658f11..7839aa373502 100644 --- a/exporter/azuremonitorexporter/trace_to_envelope.go +++ b/exporter/azuremonitorexporter/trace_to_envelope.go @@ -47,7 +47,8 @@ func spanToEnvelopes( instrumentationScope pcommon.InstrumentationScope, span ptrace.Span, spanEventsEnabled bool, - logger *zap.Logger) ([]*contracts.Envelope, error) { + logger *zap.Logger, +) ([]*contracts.Envelope, error) { spanKind := span.Kind() // According to the SpanKind documentation, we can assume it to be INTERNAL @@ -550,7 +551,8 @@ func fillRemoteDependencyDataMessaging(span ptrace.Span, data *contracts.RemoteD func copyAndMapAttributes( attributeMap pcommon.Map, properties map[string]string, - mappingFunc func(k string, v pcommon.Value)) { + mappingFunc func(k string, v pcommon.Value), +) { attributeMap.Range(func(k string, v pcommon.Value) bool { setAttributeValueAsProperty(k, v, properties) if mappingFunc != nil { @@ -563,14 +565,16 @@ func copyAndMapAttributes( // Copies all attributes to either properties or measurements without any kind of mapping to a known set of attributes func copyAttributesWithoutMapping( attributeMap pcommon.Map, - properties map[string]string) { + properties map[string]string, +) { copyAndMapAttributes(attributeMap, properties, nil) } // Attribute extraction logic for HTTP Span attributes func copyAndExtractHTTPAttributes( attributeMap pcommon.Map, - properties map[string]string) *HTTPAttributes { + properties map[string]string, +) *HTTPAttributes { attrs := &HTTPAttributes{} copyAndMapAttributes( attributeMap, @@ -583,7 +587,8 @@ func copyAndExtractHTTPAttributes( // Attribute extraction logic for RPC Span attributes func copyAndExtractRPCAttributes( attributeMap pcommon.Map, - properties map[string]string) *RPCAttributes { + properties map[string]string, +) *RPCAttributes { attrs := &RPCAttributes{} copyAndMapAttributes( attributeMap, @@ -596,7 +601,8 @@ func copyAndExtractRPCAttributes( // Attribute extraction logic for Database Span attributes func copyAndExtractDatabaseAttributes( attributeMap pcommon.Map, - properties map[string]string) *DatabaseAttributes { + properties map[string]string, +) *DatabaseAttributes { attrs := &DatabaseAttributes{} copyAndMapAttributes( attributeMap, @@ -609,7 +615,8 @@ func copyAndExtractDatabaseAttributes( // Attribute extraction logic for Messaging Span attributes func copyAndExtractMessagingAttributes( attributeMap pcommon.Map, - properties map[string]string) *MessagingAttributes { + properties map[string]string, +) *MessagingAttributes { attrs := &MessagingAttributes{} copyAndMapAttributes( attributeMap, @@ -622,7 +629,8 @@ func copyAndExtractMessagingAttributes( // Attribute extraction logic for Span event exception attributes func copyAndExtractExceptionAttributes( attributeMap pcommon.Map, - properties map[string]string) *ExceptionAttributes { + properties map[string]string, +) *ExceptionAttributes { attrs := &ExceptionAttributes{} copyAndMapAttributes( attributeMap, @@ -696,7 +704,8 @@ func writeFormattedPeerAddressFromNetworkAttributes(networkAttributes *NetworkAt func setAttributeValueAsProperty( key string, attributeValue pcommon.Value, - properties map[string]string) { + properties map[string]string, +) { switch attributeValue.Type() { case pcommon.ValueTypeBool: properties[key] = strconv.FormatBool(attributeValue.Bool()) diff --git a/exporter/azuremonitorexporter/trace_to_envelope_test.go b/exporter/azuremonitorexporter/trace_to_envelope_test.go index 441919546f64..2390e71e48d4 100644 --- a/exporter/azuremonitorexporter/trace_to_envelope_test.go +++ b/exporter/azuremonitorexporter/trace_to_envelope_test.go @@ -566,7 +566,8 @@ func commonEnvelopeValidations( t *testing.T, span ptrace.Span, envelope *contracts.Envelope, - expectedEnvelopeName string) { + expectedEnvelopeName string, +) { assert.NotNil(t, envelope) assert.Equal(t, expectedEnvelopeName, envelope.Name) assert.Equal(t, toTime(span.StartTimestamp()).Format(time.RFC3339Nano), envelope.Time) @@ -587,7 +588,8 @@ func commonEnvelopeValidations( func commonRequestDataValidations( t *testing.T, span ptrace.Span, - data *contracts.RequestData) { + data *contracts.RequestData, +) { assertAttributesCopiedToProperties(t, span.Attributes(), data.Properties) assert.Equal(t, defaultSpanIDAsHex, data.Id) assert.Equal(t, defaultSpanDuration, data.Duration) @@ -600,7 +602,8 @@ func commonRequestDataValidations( func defaultHTTPRequestDataValidations( t *testing.T, span ptrace.Span, - data *contracts.RequestData) { + data *contracts.RequestData, +) { commonRequestDataValidations(t, span, data) assert.Equal(t, defaultHTTPStatusCodeAsString, data.ResponseCode) @@ -612,7 +615,8 @@ func defaultHTTPRequestDataValidations( func commonRemoteDependencyDataValidations( t *testing.T, span ptrace.Span, - data *contracts.RemoteDependencyData) { + data *contracts.RemoteDependencyData, +) { assertAttributesCopiedToProperties(t, span.Attributes(), data.Properties) assert.Equal(t, defaultSpanIDAsHex, data.Id) assert.Equal(t, defaultSpanDuration, data.Duration) @@ -622,7 +626,8 @@ func commonRemoteDependencyDataValidations( func defaultHTTPRemoteDependencyDataValidations( t *testing.T, span ptrace.Span, - data *contracts.RemoteDependencyData) { + data *contracts.RemoteDependencyData, +) { commonRemoteDependencyDataValidations(t, span, data) assert.Equal(t, defaultHTTPStatusCodeAsString, data.ResultCode) @@ -635,7 +640,8 @@ func defaultRPCRequestDataValidations( t *testing.T, span ptrace.Span, data *contracts.RequestData, - expectedDataSource string) { + expectedDataSource string, +) { commonRequestDataValidations(t, span, data) assert.Equal(t, defaultRPCStatusCodeAsString, data.ResponseCode) @@ -649,7 +655,8 @@ func defaultRPCRemoteDependencyDataValidations( t *testing.T, span ptrace.Span, data *contracts.RemoteDependencyData, - expectedDataTarget string) { + expectedDataTarget string, +) { commonRemoteDependencyDataValidations(t, span, data) assert.Equal(t, defaultRPCStatusCodeAsString, data.ResultCode) @@ -665,7 +672,8 @@ func defaultRPCRemoteDependencyDataValidations( func defaultDatabaseRemoteDependencyDataValidations( t *testing.T, span ptrace.Span, - data *contracts.RemoteDependencyData) { + data *contracts.RemoteDependencyData, +) { commonRemoteDependencyDataValidations(t, span, data) assert.Equal(t, defaultDatabaseStatusCodeAsString, data.ResultCode) @@ -677,7 +685,8 @@ func defaultDatabaseRemoteDependencyDataValidations( func defaultMessagingRequestDataValidations( t *testing.T, span ptrace.Span, - data *contracts.RequestData) { + data *contracts.RequestData, +) { commonRequestDataValidations(t, span, data) assert.Equal(t, defaultMessagingStatusCodeAsString, data.ResponseCode) @@ -688,7 +697,8 @@ func defaultMessagingRequestDataValidations( func defaultMessagingRemoteDependencyDataValidations( t *testing.T, span ptrace.Span, - data *contracts.RemoteDependencyData) { + data *contracts.RemoteDependencyData, +) { commonRemoteDependencyDataValidations(t, span, data) assert.Equal(t, defaultMessagingStatusCodeAsString, data.ResultCode) @@ -700,7 +710,8 @@ func defaultMessagingRemoteDependencyDataValidations( func defaultInternalRemoteDependencyDataValidations( t *testing.T, span ptrace.Span, - data *contracts.RemoteDependencyData) { + data *contracts.RemoteDependencyData, +) { assertAttributesCopiedToProperties(t, span.Attributes(), data.Properties) assert.Equal(t, "InProc", data.Type) } @@ -709,7 +720,8 @@ func defaultInternalRemoteDependencyDataValidations( func assertAttributesCopiedToProperties( t *testing.T, attributeMap pcommon.Map, - properties map[string]string) { + properties map[string]string, +) { attributeMap.Range(func(k string, v pcommon.Value) bool { p, exists := properties[k] assert.True(t, exists) diff --git a/exporter/azuremonitorexporter/traceexporter.go b/exporter/azuremonitorexporter/traceexporter.go index 3dedaf1ee551..f5eb15d4e2f1 100644 --- a/exporter/azuremonitorexporter/traceexporter.go +++ b/exporter/azuremonitorexporter/traceexporter.go @@ -30,7 +30,8 @@ type traceVisitor struct { func (v *traceVisitor) visit( resource pcommon.Resource, scope pcommon.InstrumentationScope, - span ptrace.Span) (ok bool) { + span ptrace.Span, +) (ok bool) { envelopes, err := spanToEnvelopes(resource, scope, span, v.exporter.config.SpanEventsEnabled, v.exporter.logger) if err != nil { // record the error and short-circuit diff --git a/exporter/azuremonitorexporter/traceexporter_test.go b/exporter/azuremonitorexporter/traceexporter_test.go index a4fc97be457d..c80a78cb8f29 100644 --- a/exporter/azuremonitorexporter/traceexporter_test.go +++ b/exporter/azuremonitorexporter/traceexporter_test.go @@ -15,9 +15,7 @@ import ( "golang.org/x/net/context" ) -var ( - defaultConfig = createDefaultConfig().(*Config) -) +var defaultConfig = createDefaultConfig().(*Config) // Tests the export onTraceData callback with no Spans func TestExporterTraceDataCallbackNoSpans(t *testing.T) { diff --git a/exporter/carbonexporter/config_test.go b/exporter/carbonexporter/config_test.go index fd0d0c0c3759..795f0622d702 100644 --- a/exporter/carbonexporter/config_test.go +++ b/exporter/carbonexporter/config_test.go @@ -31,7 +31,6 @@ func TestLoadConfig(t *testing.T) { expected component.Config errorMessage string }{ - { id: component.NewIDWithName(metadata.Type, ""), expected: createDefaultConfig(), diff --git a/exporter/carbonexporter/factory.go b/exporter/carbonexporter/factory.go index 6343eb2502fa..5622d8627482 100644 --- a/exporter/carbonexporter/factory.go +++ b/exporter/carbonexporter/factory.go @@ -46,7 +46,6 @@ func createMetricsExporter( config component.Config, ) (exporter.Metrics, error) { exp, err := newCarbonExporter(ctx, config.(*Config), params) - if err != nil { return nil, err } diff --git a/exporter/cassandraexporter/config_test.go b/exporter/cassandraexporter/config_test.go index 41799aa6c579..a00d6d21e7af 100644 --- a/exporter/cassandraexporter/config_test.go +++ b/exporter/cassandraexporter/config_test.go @@ -15,8 +15,10 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/cassandraexporter/internal/metadata" ) -const defaultDSN = "127.0.0.1" -const defaultPort = 9042 +const ( + defaultDSN = "127.0.0.1" + defaultPort = 9042 +) func TestLoadConfig(t *testing.T) { t.Parallel() @@ -32,7 +34,6 @@ func TestLoadConfig(t *testing.T) { id component.ID expected component.Config }{ - { id: component.NewIDWithName(metadata.Type, ""), expected: defaultCfg, diff --git a/exporter/clickhouseexporter/config.go b/exporter/clickhouseexporter/config.go index f21d96a77830..05ddf2e09903 100644 --- a/exporter/clickhouseexporter/config.go +++ b/exporter/clickhouseexporter/config.go @@ -81,14 +81,16 @@ type TableEngine struct { Params string `mapstructure:"params"` } -const defaultDatabase = "default" -const defaultTableEngineName = "MergeTree" -const defaultMetricTableName = "otel_metrics" -const defaultGaugeSuffix = "_gauge" -const defaultSumSuffix = "_sum" -const defaultSummarySuffix = "_summary" -const defaultHistogramSuffix = "_histogram" -const defaultExpHistogramSuffix = "_exponential_histogram" +const ( + defaultDatabase = "default" + defaultTableEngineName = "MergeTree" + defaultMetricTableName = "otel_metrics" + defaultGaugeSuffix = "_gauge" + defaultSumSuffix = "_sum" + defaultSummarySuffix = "_summary" + defaultHistogramSuffix = "_histogram" + defaultExpHistogramSuffix = "_exponential_histogram" +) var ( errConfigNoEndpoint = errors.New("endpoint must be specified") diff --git a/exporter/clickhouseexporter/config_test.go b/exporter/clickhouseexporter/config_test.go index 233d73abe232..b3167ed52fc7 100644 --- a/exporter/clickhouseexporter/config_test.go +++ b/exporter/clickhouseexporter/config_test.go @@ -40,7 +40,6 @@ func TestLoadConfig(t *testing.T) { id component.ID expected component.Config }{ - { id: component.NewIDWithName(metadata.Type, ""), expected: defaultCfg, diff --git a/exporter/clickhouseexporter/exporter_logs_test.go b/exporter/clickhouseexporter/exporter_logs_test.go index 5ab742e32b68..2332f7e8a9fb 100644 --- a/exporter/clickhouseexporter/exporter_logs_test.go +++ b/exporter/clickhouseexporter/exporter_logs_test.go @@ -283,8 +283,7 @@ func (t *testClickhouseDriverStmt) Query(_ []driver.Value) (driver.Rows, error) return nil, nil } -type testClickhouseDriverTx struct { -} +type testClickhouseDriverTx struct{} func (*testClickhouseDriverTx) Commit() error { return nil diff --git a/exporter/clickhouseexporter/exporter_sql_test.go b/exporter/clickhouseexporter/exporter_sql_test.go index 0a01b1c284ef..b2c3942b7542 100644 --- a/exporter/clickhouseexporter/exporter_sql_test.go +++ b/exporter/clickhouseexporter/exporter_sql_test.go @@ -13,12 +13,14 @@ import ( "github.com/stretchr/testify/require" ) -type clusterTestCompletion func(t *testing.T, dsn string, clusterTest clusterTestConfig, fns ...func(*Config)) -type clusterTestConfig struct { - name string - cluster string - shouldPass bool -} +type ( + clusterTestCompletion func(t *testing.T, dsn string, clusterTest clusterTestConfig, fns ...func(*Config)) + clusterTestConfig struct { + name string + cluster string + shouldPass bool + } +) func (test clusterTestConfig) verifyConfig(t *testing.T, cfg *Config) { if test.cluster == "" { @@ -86,14 +88,16 @@ func testClusterConfig(t *testing.T, completion clusterTestCompletion) { } } -type tableEngineTestCompletion func(t *testing.T, dsn string, engineTest tableEngineTestConfig, fns ...func(*Config)) -type tableEngineTestConfig struct { - name string - engineName string - engineParams string - expectedTableName string - shouldPass bool -} +type ( + tableEngineTestCompletion func(t *testing.T, dsn string, engineTest tableEngineTestConfig, fns ...func(*Config)) + tableEngineTestConfig struct { + name string + engineName string + engineParams string + expectedTableName string + shouldPass bool + } +) func (engineTest tableEngineTestConfig) verifyConfig(t *testing.T, te TableEngine) { if engineTest.engineName == "" { diff --git a/exporter/coralogixexporter/config.go b/exporter/coralogixexporter/config.go index 0c786d20710d..df679be3c5d0 100644 --- a/exporter/coralogixexporter/config.go +++ b/exporter/coralogixexporter/config.go @@ -63,6 +63,7 @@ func isEmpty(endpoint string) bool { } return false } + func (c *Config) Validate() error { // validate that at least one endpoint is set up correctly if isEmpty(c.Domain) && diff --git a/exporter/coralogixexporter/traces_client.go b/exporter/coralogixexporter/traces_client.go index e3ce96d81c86..2b5665624687 100644 --- a/exporter/coralogixexporter/traces_client.go +++ b/exporter/coralogixexporter/traces_client.go @@ -89,6 +89,7 @@ func (e *tracesExporter) pushTraces(ctx context.Context, td ptrace.Traces) error return nil } + func (e *tracesExporter) shutdown(context.Context) error { if e.clientConn == nil { return nil diff --git a/exporter/datadogexporter/internal/clientutil/http_test.go b/exporter/datadogexporter/internal/clientutil/http_test.go index 95fa023a6965..1327b85279c4 100644 --- a/exporter/datadogexporter/internal/clientutil/http_test.go +++ b/exporter/datadogexporter/internal/clientutil/http_test.go @@ -19,12 +19,10 @@ import ( "go.opentelemetry.io/collector/config/configtls" ) -var ( - buildInfo = component.BuildInfo{ - Command: "otelcontribcol", - Version: "1.0", - } -) +var buildInfo = component.BuildInfo{ + Command: "otelcontribcol", + Version: "1.0", +} func TestNewHTTPClient(t *testing.T) { hcsEmpty := confighttp.ClientConfig{} diff --git a/exporter/datadogexporter/internal/hostmetadata/host.go b/exporter/datadogexporter/internal/hostmetadata/host.go index c99e689ac73b..99f267afc39c 100644 --- a/exporter/datadogexporter/internal/hostmetadata/host.go +++ b/exporter/datadogexporter/internal/hostmetadata/host.go @@ -72,7 +72,6 @@ func GetSourceProvider(set component.TelemetrySettings, configHostname string, t []string{"config", "azure", "ecs", "ec2", "gcp", "kubernetes", "system"}, timeout, ) - if err != nil { return nil, err } diff --git a/exporter/datadogexporter/internal/hostmetadata/internal/azure/provider.go b/exporter/datadogexporter/internal/hostmetadata/internal/azure/provider.go index bf66f14273ad..e6decc49f9be 100644 --- a/exporter/datadogexporter/internal/hostmetadata/internal/azure/provider.go +++ b/exporter/datadogexporter/internal/hostmetadata/internal/azure/provider.go @@ -15,8 +15,10 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/internal/metadataproviders/azure" ) -var _ source.Provider = (*Provider)(nil) -var _ provider.ClusterNameProvider = (*Provider)(nil) +var ( + _ source.Provider = (*Provider)(nil) + _ provider.ClusterNameProvider = (*Provider)(nil) +) type Provider struct { detector azure.Provider diff --git a/exporter/datadogexporter/internal/hostmetadata/internal/ec2/ec2.go b/exporter/datadogexporter/internal/hostmetadata/internal/ec2/ec2.go index d0920ecc5856..ef20a5382106 100644 --- a/exporter/datadogexporter/internal/hostmetadata/internal/ec2/ec2.go +++ b/exporter/datadogexporter/internal/hostmetadata/internal/ec2/ec2.go @@ -21,9 +21,7 @@ import ( ec2provider "github.com/open-telemetry/opentelemetry-collector-contrib/internal/metadataproviders/aws/ec2" ) -var ( - defaultPrefixes = [3]string{"ip-", "domu", "ec2amaz-"} -) +var defaultPrefixes = [3]string{"ip-", "domu", "ec2amaz-"} type HostInfo struct { InstanceID string @@ -82,8 +80,10 @@ func (hi *HostInfo) GetHostname(_ *zap.Logger) string { return hi.EC2Hostname } -var _ source.Provider = (*Provider)(nil) -var _ provider.ClusterNameProvider = (*Provider)(nil) +var ( + _ source.Provider = (*Provider)(nil) + _ provider.ClusterNameProvider = (*Provider)(nil) +) type Provider struct { once sync.Once diff --git a/exporter/datadogexporter/internal/hostmetadata/internal/gcp/provider.go b/exporter/datadogexporter/internal/hostmetadata/internal/gcp/provider.go index 5951494a804a..eeb7fb7c046b 100644 --- a/exporter/datadogexporter/internal/hostmetadata/internal/gcp/provider.go +++ b/exporter/datadogexporter/internal/hostmetadata/internal/gcp/provider.go @@ -15,8 +15,10 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/datadogexporter/internal/hostmetadata/provider" ) -var _ source.Provider = (*Provider)(nil) -var _ provider.ClusterNameProvider = (*Provider)(nil) +var ( + _ source.Provider = (*Provider)(nil) + _ provider.ClusterNameProvider = (*Provider)(nil) +) var _ gcpDetector = gcp.NewDetector() diff --git a/exporter/datadogexporter/internal/hostmetadata/internal/k8s/nodename.go b/exporter/datadogexporter/internal/hostmetadata/internal/k8s/nodename.go index 70c919da2de6..2431b2a9c3f7 100644 --- a/exporter/datadogexporter/internal/hostmetadata/internal/k8s/nodename.go +++ b/exporter/datadogexporter/internal/hostmetadata/internal/k8s/nodename.go @@ -70,7 +70,6 @@ func newNodeNameProvider() nodeNameProvider { client, err := k8sconfig.MakeClient(k8sconfig.APIConfig{ AuthType: k8sconfig.AuthTypeServiceAccount, }) - if err != nil { return &nodeNameUnavailable{err: err} } diff --git a/exporter/datadogexporter/internal/hostmetadata/internal/k8s/provider_test.go b/exporter/datadogexporter/internal/hostmetadata/internal/k8s/provider_test.go index cda386036f59..2f168604b1c3 100644 --- a/exporter/datadogexporter/internal/hostmetadata/internal/k8s/provider_test.go +++ b/exporter/datadogexporter/internal/hostmetadata/internal/k8s/provider_test.go @@ -15,16 +15,20 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/datadogexporter/internal/hostmetadata/provider" ) -var _ provider.ClusterNameProvider = (*StringProvider)(nil) -var _ nodeNameProvider = (*StringProvider)(nil) +var ( + _ provider.ClusterNameProvider = (*StringProvider)(nil) + _ nodeNameProvider = (*StringProvider)(nil) +) type StringProvider string func (p StringProvider) ClusterName(context.Context) (string, error) { return string(p), nil } func (p StringProvider) NodeName(context.Context) (string, error) { return string(p), nil } -var _ provider.ClusterNameProvider = (*ErrorProvider)(nil) -var _ nodeNameProvider = (*ErrorProvider)(nil) +var ( + _ provider.ClusterNameProvider = (*ErrorProvider)(nil) + _ nodeNameProvider = (*ErrorProvider)(nil) +) type ErrorProvider string diff --git a/exporter/datadogexporter/internal/metrics/consumer.go b/exporter/datadogexporter/internal/metrics/consumer.go index ae00f7237034..2d43e604ea5d 100644 --- a/exporter/datadogexporter/internal/metrics/consumer.go +++ b/exporter/datadogexporter/internal/metrics/consumer.go @@ -15,9 +15,11 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/datadogexporter/internal/metrics/sketches" ) -var _ metrics.Consumer = (*Consumer)(nil) -var _ metrics.HostConsumer = (*Consumer)(nil) -var _ metrics.TagsConsumer = (*Consumer)(nil) +var ( + _ metrics.Consumer = (*Consumer)(nil) + _ metrics.HostConsumer = (*Consumer)(nil) + _ metrics.TagsConsumer = (*Consumer)(nil) +) // Consumer implements metrics.Consumer. It records consumed metrics, sketches and // APM stats payloads. It provides them to the caller using the All method. diff --git a/exporter/datadogexporter/internal/metrics/consumer_deprecated.go b/exporter/datadogexporter/internal/metrics/consumer_deprecated.go index c47c2acda3a6..0b71f2c98d88 100644 --- a/exporter/datadogexporter/internal/metrics/consumer_deprecated.go +++ b/exporter/datadogexporter/internal/metrics/consumer_deprecated.go @@ -14,9 +14,11 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/datadogexporter/internal/metrics/sketches" ) -var _ metrics.Consumer = (*ZorkianConsumer)(nil) -var _ metrics.HostConsumer = (*ZorkianConsumer)(nil) -var _ metrics.TagsConsumer = (*ZorkianConsumer)(nil) +var ( + _ metrics.Consumer = (*ZorkianConsumer)(nil) + _ metrics.HostConsumer = (*ZorkianConsumer)(nil) + _ metrics.TagsConsumer = (*ZorkianConsumer)(nil) +) // ZorkianConsumer implements metrics.Consumer. It records consumed metrics, sketches and // APM stats payloads. It provides them to the caller using the All method. diff --git a/exporter/datasetexporter/config.go b/exporter/datasetexporter/config.go index c489758bef36..ffc61e1401c0 100644 --- a/exporter/datasetexporter/config.go +++ b/exporter/datasetexporter/config.go @@ -18,8 +18,10 @@ import ( "go.opentelemetry.io/collector/exporter/exporterhelper" ) -const exportSeparatorDefault = "." -const exportDistinguishingSuffix = "_" +const ( + exportSeparatorDefault = "." + exportDistinguishingSuffix = "_" +) // exportSettings configures separator and distinguishing suffixes for all exported fields type exportSettings struct { @@ -52,12 +54,14 @@ func newDefaultTracesSettings() TracesSettings { } } -const logsExportResourceInfoDefault = false -const logsExportResourcePrefixDefault = "resource.attributes." -const logsExportScopeInfoDefault = true -const logsExportScopePrefixDefault = "scope.attributes." -const logsDecomposeComplexMessageFieldDefault = false -const logsDecomposedComplexMessageFieldPrefixDefault = "body.map." +const ( + logsExportResourceInfoDefault = false + logsExportResourcePrefixDefault = "resource.attributes." + logsExportScopeInfoDefault = true + logsExportScopePrefixDefault = "scope.attributes." + logsDecomposeComplexMessageFieldDefault = false + logsDecomposedComplexMessageFieldPrefixDefault = "body.map." +) type LogsSettings struct { // ExportResourceInfo is optional flag to signal that the resource info is being exported to DataSet while exporting Logs. @@ -105,13 +109,15 @@ func newDefaultLogsSettings() LogsSettings { } } -const bufferMaxLifetime = 5 * time.Second -const bufferPurgeOlderThan = 30 * time.Second -const bufferRetryInitialInterval = 5 * time.Second -const bufferRetryMaxInterval = 30 * time.Second -const bufferRetryMaxElapsedTime = 300 * time.Second -const bufferRetryShutdownTimeout = 30 * time.Second -const bufferMaxParallelOutgoing = 100 +const ( + bufferMaxLifetime = 5 * time.Second + bufferPurgeOlderThan = 30 * time.Second + bufferRetryInitialInterval = 5 * time.Second + bufferRetryMaxInterval = 30 * time.Second + bufferRetryMaxElapsedTime = 300 * time.Second + bufferRetryShutdownTimeout = 30 * time.Second + bufferMaxParallelOutgoing = 100 +) type BufferSettings struct { MaxLifetime time.Duration `mapstructure:"max_lifetime"` diff --git a/exporter/datasetexporter/logs_exporter_test.go b/exporter/datasetexporter/logs_exporter_test.go index 3b8c6e3a4ee7..c07b44c27781 100644 --- a/exporter/datasetexporter/logs_exporter_test.go +++ b/exporter/datasetexporter/logs_exporter_test.go @@ -672,6 +672,7 @@ func TestBuildEventFromLogExportScopeInfo(t *testing.T) { assert.Equal(t, expected, was) } + func TestBuildEventFromLogEventWithoutTimestampWithObservedTimestampUseObservedTimestamp(t *testing.T) { // When LogRecord doesn't have timestamp set, but it has ObservedTimestamp set, // ObservedTimestamp should be used diff --git a/exporter/datasetexporter/traces_exporter.go b/exporter/datasetexporter/traces_exporter.go index 04382e2be245..c1fde0ae0935 100644 --- a/exporter/datasetexporter/traces_exporter.go +++ b/exporter/datasetexporter/traces_exporter.go @@ -88,8 +88,10 @@ func buildEventFromSpan( } } -const resourceName = "resource_name" -const resourceType = "resource_type" +const ( + resourceName = "resource_name" + resourceType = "resource_type" +) type ResourceType string @@ -134,7 +136,7 @@ type spanBundle struct { } func buildEventsFromTraces(ld ptrace.Traces, serverHost string, settings TracesSettings) []*add_events.EventBundle { - var spans = make([]spanBundle, 0) + spans := make([]spanBundle, 0) // convert spans into events resourceSpans := ld.ResourceSpans() diff --git a/exporter/datasetexporter/traces_exporter_test.go b/exporter/datasetexporter/traces_exporter_test.go index f74c8f63c0b5..0c905ce021cf 100644 --- a/exporter/datasetexporter/traces_exporter_test.go +++ b/exporter/datasetexporter/traces_exporter_test.go @@ -433,29 +433,41 @@ func TestBuildEventsFromTracesFromTwoSpansSameResourceOneDifferent(t *testing.T) assert.Equal(t, expected, was) } -var span0Id = [8]byte{1, 1, 1, 1, 1, 1, 1, 1} -var span00Id = [8]byte{1, 2, 1, 1, 1, 1, 1, 1} -var span01Id = [8]byte{1, 3, 1, 1, 1, 1, 1, 1} -var span000Id = [8]byte{1, 2, 2, 1, 1, 1, 1, 1} -var span001Id = [8]byte{1, 2, 3, 1, 1, 1, 1, 1} -var span002Id = [8]byte{1, 2, 4, 1, 1, 1, 1, 1} +var ( + span0Id = [8]byte{1, 1, 1, 1, 1, 1, 1, 1} + span00Id = [8]byte{1, 2, 1, 1, 1, 1, 1, 1} + span01Id = [8]byte{1, 3, 1, 1, 1, 1, 1, 1} + span000Id = [8]byte{1, 2, 2, 1, 1, 1, 1, 1} + span001Id = [8]byte{1, 2, 3, 1, 1, 1, 1, 1} + span002Id = [8]byte{1, 2, 4, 1, 1, 1, 1, 1} +) -var span1Id = [8]byte{2, 2, 2, 2, 2, 2, 2, 2} -var span10Id = [8]byte{2, 3, 2, 2, 2, 2, 2, 2} +var ( + span1Id = [8]byte{2, 2, 2, 2, 2, 2, 2, 2} + span10Id = [8]byte{2, 3, 2, 2, 2, 2, 2, 2} +) -var span21Id = [8]byte{3, 3, 3, 3, 3, 3, 3, 3} -var span22Id = [8]byte{3, 4, 3, 3, 3, 3, 3, 3} +var ( + span21Id = [8]byte{3, 3, 3, 3, 3, 3, 3, 3} + span22Id = [8]byte{3, 4, 3, 3, 3, 3, 3, 3} +) -var span21PId = [8]byte{3, 5, 3, 3, 3, 3, 3, 3} -var span22PId = [8]byte{3, 6, 3, 3, 3, 3, 3, 3} +var ( + span21PId = [8]byte{3, 5, 3, 3, 3, 3, 3, 3} + span22PId = [8]byte{3, 6, 3, 3, 3, 3, 3, 3} +) -var span3Id = [8]byte{4, 4, 4, 4, 4, 4, 4, 4} -var span30Id = [8]byte{4, 5, 4, 4, 4, 4, 4, 4} +var ( + span3Id = [8]byte{4, 4, 4, 4, 4, 4, 4, 4} + span30Id = [8]byte{4, 5, 4, 4, 4, 4, 4, 4} +) -var trace0Id = [16]byte{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1} -var trace1Id = [16]byte{2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2} -var trace2Id = [16]byte{3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3} -var trace3Id = [16]byte{4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4} +var ( + trace0Id = [16]byte{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1} + trace1Id = [16]byte{2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2} + trace2Id = [16]byte{3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3} + trace3Id = [16]byte{4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4} +) func generateTracesTreesAndOrphans() ptrace.Traces { td := ptrace.NewTraces() diff --git a/exporter/dorisexporter/exporter_common_test.go b/exporter/dorisexporter/exporter_common_test.go index b4bef2904818..baea71b36bb9 100644 --- a/exporter/dorisexporter/exporter_common_test.go +++ b/exporter/dorisexporter/exporter_common_test.go @@ -47,7 +47,6 @@ func TestStreamLoadUrl(t *testing.T) { func findRandomPort() (int, error) { l, err := net.Listen("tcp", "localhost:0") - if err != nil { return 0, err } @@ -55,7 +54,6 @@ func findRandomPort() (int, error) { port := l.Addr().(*net.TCPAddr).Port err = l.Close() - if err != nil { return 0, err } diff --git a/exporter/elasticsearchexporter/esclient.go b/exporter/elasticsearchexporter/esclient.go index 927f62844ec3..fe99cf8a2f12 100644 --- a/exporter/elasticsearchexporter/esclient.go +++ b/exporter/elasticsearchexporter/esclient.go @@ -130,7 +130,7 @@ func newElasticsearchClient( RetryOnStatus: config.Retry.RetryOnStatus, DisableRetry: !config.Retry.Enabled, EnableRetryOnTimeout: config.Retry.Enabled, - //RetryOnError: retryOnError, // should be used from esclient version 8 onwards + // RetryOnError: retryOnError, // should be used from esclient version 8 onwards MaxRetries: maxRetries, RetryBackoff: createElasticsearchBackoffFunc(&config.Retry), diff --git a/exporter/elasticsearchexporter/internal/objmodel/objmodel.go b/exporter/elasticsearchexporter/internal/objmodel/objmodel.go index 0f6f77a4fc12..6f8a9b41add8 100644 --- a/exporter/elasticsearchexporter/internal/objmodel/objmodel.go +++ b/exporter/elasticsearchexporter/internal/objmodel/objmodel.go @@ -88,8 +88,10 @@ const ( const tsLayout = "2006-01-02T15:04:05.000000000Z" -var nilValue = Value{kind: KindNil} -var ignoreValue = Value{kind: KindIgnore} +var ( + nilValue = Value{kind: KindNil} + ignoreValue = Value{kind: KindIgnore} +) // DocumentFromAttributes creates a document from a OpenTelemetry attribute // map. All nested maps will be flattened, with keys being joined using a `.` symbol. diff --git a/exporter/elasticsearchexporter/model_test.go b/exporter/elasticsearchexporter/model_test.go index 2a813b06681a..ad414ed275fe 100644 --- a/exporter/elasticsearchexporter/model_test.go +++ b/exporter/elasticsearchexporter/model_test.go @@ -48,8 +48,10 @@ var expectedMetricsEncoded = `{"@timestamp":"2024-06-12T10:20:16.419290690Z","cp {"@timestamp":"2024-06-12T10:20:16.419290690Z","cpu":"cpu1","host":{"hostname":"my-host","name":"my-host","os":{"platform":"linux"}},"state":"user","system":{"cpu":{"time":50.09}}} {"@timestamp":"2024-06-12T10:20:16.419290690Z","cpu":"cpu1","host":{"hostname":"my-host","name":"my-host","os":{"platform":"linux"}},"state":"wait","system":{"cpu":{"time":0.95}}}` -var expectedLogBodyWithEmptyTimestamp = `{"@timestamp":"1970-01-01T00:00:00.000000000Z","Attributes.log-attr1":"value1","Body":"log-body","Resource.key1":"value1","Scope.name":"","Scope.version":"","SeverityNumber":0,"TraceFlags":0}` -var expectedLogBodyDeDottedWithEmptyTimestamp = `{"@timestamp":"1970-01-01T00:00:00.000000000Z","Attributes":{"log-attr1":"value1"},"Body":"log-body","Resource":{"foo":{"bar":"baz"},"key1":"value1"},"Scope":{"name":"","version":""},"SeverityNumber":0,"TraceFlags":0}` +var ( + expectedLogBodyWithEmptyTimestamp = `{"@timestamp":"1970-01-01T00:00:00.000000000Z","Attributes.log-attr1":"value1","Body":"log-body","Resource.key1":"value1","Scope.name":"","Scope.version":"","SeverityNumber":0,"TraceFlags":0}` + expectedLogBodyDeDottedWithEmptyTimestamp = `{"@timestamp":"1970-01-01T00:00:00.000000000Z","Attributes":{"log-attr1":"value1"},"Body":"log-body","Resource":{"foo":{"bar":"baz"},"key1":"value1"},"Scope":{"name":"","version":""},"SeverityNumber":0,"TraceFlags":0}` +) func TestEncodeSpan(t *testing.T) { model := &encodeModel{dedot: false} diff --git a/exporter/fileexporter/buffered_writer.go b/exporter/fileexporter/buffered_writer.go index 6e50b6519296..d3d8de03fc57 100644 --- a/exporter/fileexporter/buffered_writer.go +++ b/exporter/fileexporter/buffered_writer.go @@ -16,9 +16,7 @@ type bufferedWriteCloser struct { buffered *bufio.Writer } -var ( - _ io.WriteCloser = (*bufferedWriteCloser)(nil) -) +var _ io.WriteCloser = (*bufferedWriteCloser)(nil) func newBufferedWriteCloser(f io.WriteCloser) io.WriteCloser { return &bufferedWriteCloser{ diff --git a/exporter/fileexporter/buffered_writer_test.go b/exporter/fileexporter/buffered_writer_test.go index e474c4b1b3f2..ef56914076be 100644 --- a/exporter/fileexporter/buffered_writer_test.go +++ b/exporter/fileexporter/buffered_writer_test.go @@ -44,9 +44,7 @@ func TestBufferedWrites(t *testing.T) { assert.Equal(t, msg, b.String(), "Must match the expected string") } -var ( - errBenchmark error -) +var errBenchmark error func BenchmarkWriter(b *testing.B) { tempfile := func(tb testing.TB) io.WriteCloser { diff --git a/exporter/fileexporter/config.go b/exporter/fileexporter/config.go index bdd05dd278b5..43499f70e105 100644 --- a/exporter/fileexporter/config.go +++ b/exporter/fileexporter/config.go @@ -20,7 +20,6 @@ const ( // Config defines configuration for file exporter. type Config struct { - // Path of the file to write to. Path is relative to current directory. Path string `mapstructure:"path"` diff --git a/exporter/fileexporter/encoding_test.go b/exporter/fileexporter/encoding_test.go index 817e9c414ee9..e8729e0077fd 100644 --- a/exporter/fileexporter/encoding_test.go +++ b/exporter/fileexporter/encoding_test.go @@ -58,7 +58,6 @@ func TestEncoding(t *testing.T) { require.NoError(t, te.Start(context.Background(), host)) require.NoError(t, le.Start(context.Background(), host)) t.Cleanup(func() { - }) require.NoError(t, me.ConsumeMetrics(context.Background(), generateMetrics())) diff --git a/exporter/fileexporter/factory.go b/exporter/fileexporter/factory.go index 606a9386d0bb..e59b54d7319f 100644 --- a/exporter/fileexporter/factory.go +++ b/exporter/fileexporter/factory.go @@ -154,7 +154,7 @@ func newFileWriter(path string, shouldAppend bool, rotation *Rotation, flushInte } else { fileFlags |= os.O_TRUNC } - f, err := os.OpenFile(path, fileFlags, 0644) + f, err := os.OpenFile(path, fileFlags, 0o644) if err != nil { return nil, err } diff --git a/exporter/fileexporter/file_exporter_test.go b/exporter/fileexporter/file_exporter_test.go index a6ec7a5bfc9d..87cecf02ed94 100644 --- a/exporter/fileexporter/file_exporter_test.go +++ b/exporter/fileexporter/file_exporter_test.go @@ -484,8 +484,7 @@ func tempFileName(t testing.TB) string { } // errorWriter is an io.Writer that will return an error all ways -type errorWriter struct { -} +type errorWriter struct{} func (e errorWriter) Write([]byte) (n int, err error) { return 0, errors.New("all ways return error") diff --git a/exporter/fileexporter/grouping_file_exporter.go b/exporter/fileexporter/grouping_file_exporter.go index 329c61878577..322fef47e00b 100644 --- a/exporter/fileexporter/grouping_file_exporter.go +++ b/exporter/fileexporter/grouping_file_exporter.go @@ -175,7 +175,7 @@ func (e *groupingFileExporter) getWriter(pathSegment string) (*fileWriter, error return writer, nil } - err := os.MkdirAll(path.Dir(fullPath), 0755) + err := os.MkdirAll(path.Dir(fullPath), 0o755) if err != nil { return nil, err } diff --git a/exporter/fileexporter/marshaller.go b/exporter/fileexporter/marshaller.go index e3452b93ee64..d80325d735a0 100644 --- a/exporter/fileexporter/marshaller.go +++ b/exporter/fileexporter/marshaller.go @@ -18,10 +18,12 @@ var tracesMarshalers = map[string]ptrace.Marshaler{ formatTypeJSON: &ptrace.JSONMarshaler{}, formatTypeProto: &ptrace.ProtoMarshaler{}, } + var metricsMarshalers = map[string]pmetric.Marshaler{ formatTypeJSON: &pmetric.JSONMarshaler{}, formatTypeProto: &pmetric.ProtoMarshaler{}, } + var logsMarshalers = map[string]plog.Marshaler{ formatTypeJSON: &plog.JSONMarshaler{}, formatTypeProto: &plog.ProtoMarshaler{}, diff --git a/exporter/googlecloudexporter/factory.go b/exporter/googlecloudexporter/factory.go index 13779af801d9..fd35483a4856 100644 --- a/exporter/googlecloudexporter/factory.go +++ b/exporter/googlecloudexporter/factory.go @@ -54,7 +54,8 @@ func createDefaultConfig() component.Config { func createLogsExporter( ctx context.Context, params exporter.Settings, - cfg component.Config) (exporter.Logs, error) { + cfg component.Config, +) (exporter.Logs, error) { eCfg := cfg.(*Config) logsExporter, err := collector.NewGoogleCloudLogsExporter(ctx, eCfg.Config, params.TelemetrySettings.Logger, params.TelemetrySettings.MeterProvider, params.BuildInfo.Version, eCfg.TimeoutSettings.Timeout) if err != nil { @@ -79,7 +80,8 @@ func createLogsExporter( func createTracesExporter( ctx context.Context, params exporter.Settings, - cfg component.Config) (exporter.Traces, error) { + cfg component.Config, +) (exporter.Traces, error) { eCfg := cfg.(*Config) tExp, err := collector.NewGoogleCloudTracesExporter(ctx, eCfg.Config, params.TelemetrySettings.Logger, params.TelemetrySettings.MeterProvider, params.BuildInfo.Version, eCfg.TimeoutSettings.Timeout) if err != nil { @@ -104,7 +106,8 @@ func createTracesExporter( func createMetricsExporter( ctx context.Context, params exporter.Settings, - cfg component.Config) (exporter.Metrics, error) { + cfg component.Config, +) (exporter.Metrics, error) { eCfg := cfg.(*Config) mExp, err := collector.NewGoogleCloudMetricsExporter(ctx, eCfg.Config, params.TelemetrySettings.Logger, params.TelemetrySettings.MeterProvider, params.BuildInfo.Version, eCfg.TimeoutSettings.Timeout) if err != nil { diff --git a/exporter/googlecloudpubsubexporter/factory.go b/exporter/googlecloudpubsubexporter/factory.go index abd991718d24..3ee84921ff9e 100644 --- a/exporter/googlecloudpubsubexporter/factory.go +++ b/exporter/googlecloudpubsubexporter/factory.go @@ -84,7 +84,8 @@ func createDefaultConfig() component.Config { func createTracesExporter( ctx context.Context, set exporter.Settings, - cfg component.Config) (exporter.Traces, error) { + cfg component.Config, +) (exporter.Traces, error) { pCfg := cfg.(*Config) pubsubExporter := ensureExporter(set, pCfg) @@ -105,7 +106,8 @@ func createTracesExporter( func createMetricsExporter( ctx context.Context, set exporter.Settings, - cfg component.Config) (exporter.Metrics, error) { + cfg component.Config, +) (exporter.Metrics, error) { pCfg := cfg.(*Config) pubsubExporter := ensureExporter(set, pCfg) return exporterhelper.NewMetrics( @@ -125,7 +127,8 @@ func createMetricsExporter( func createLogsExporter( ctx context.Context, set exporter.Settings, - cfg component.Config) (exporter.Logs, error) { + cfg component.Config, +) (exporter.Logs, error) { pCfg := cfg.(*Config) pubsubExporter := ensureExporter(set, pCfg) diff --git a/exporter/googlecloudpubsubexporter/watermark.go b/exporter/googlecloudpubsubexporter/watermark.go index d363fa40b8fd..66997204832f 100644 --- a/exporter/googlecloudpubsubexporter/watermark.go +++ b/exporter/googlecloudpubsubexporter/watermark.go @@ -12,9 +12,11 @@ import ( "go.opentelemetry.io/collector/pdata/ptrace" ) -type metricsWatermarkFunc func(metrics pmetric.Metrics, processingTime time.Time, allowedDrift time.Duration) time.Time -type logsWatermarkFunc func(logs plog.Logs, processingTime time.Time, allowedDrift time.Duration) time.Time -type tracesWatermarkFunc func(traces ptrace.Traces, processingTime time.Time, allowedDrift time.Duration) time.Time +type ( + metricsWatermarkFunc func(metrics pmetric.Metrics, processingTime time.Time, allowedDrift time.Duration) time.Time + logsWatermarkFunc func(logs plog.Logs, processingTime time.Time, allowedDrift time.Duration) time.Time + tracesWatermarkFunc func(traces ptrace.Traces, processingTime time.Time, allowedDrift time.Duration) time.Time +) type collectFunc func(timestamp pcommon.Timestamp) bool diff --git a/exporter/googlemanagedprometheusexporter/factory.go b/exporter/googlemanagedprometheusexporter/factory.go index 235194ee84f1..01fd0e395bed 100644 --- a/exporter/googlemanagedprometheusexporter/factory.go +++ b/exporter/googlemanagedprometheusexporter/factory.go @@ -50,7 +50,8 @@ func createDefaultConfig() component.Config { func createMetricsExporter( ctx context.Context, params exporter.Settings, - cfg component.Config) (exporter.Metrics, error) { + cfg component.Config, +) (exporter.Metrics, error) { eCfg := cfg.(*Config) mExp, err := collector.NewGoogleCloudMetricsExporter(ctx, eCfg.GMPConfig.toCollectorConfig(), params.TelemetrySettings.Logger, params.TelemetrySettings.MeterProvider, params.BuildInfo.Version, eCfg.TimeoutSettings.Timeout) if err != nil { diff --git a/exporter/honeycombmarkerexporter/logs_exporter.go b/exporter/honeycombmarkerexporter/logs_exporter.go index c46839a5c0c6..5b1747734fa7 100644 --- a/exporter/honeycombmarkerexporter/logs_exporter.go +++ b/exporter/honeycombmarkerexporter/logs_exporter.go @@ -158,7 +158,6 @@ func (e *honeycombLogsExporter) sendMarker(ctx context.Context, m marker, logRec func (e *honeycombLogsExporter) start(ctx context.Context, host component.Host) (err error) { client, err := e.httpClientSettings.ToClient(ctx, host, e.set) - if err != nil { return err } diff --git a/exporter/kafkaexporter/factory.go b/exporter/kafkaexporter/factory.go index 851b0345e786..eb366d7cfa8b 100644 --- a/exporter/kafkaexporter/factory.go +++ b/exporter/kafkaexporter/factory.go @@ -90,8 +90,7 @@ func createDefaultConfig() component.Config { } } -type kafkaExporterFactory struct { -} +type kafkaExporterFactory struct{} func (f *kafkaExporterFactory) createTracesExporter( ctx context.Context, diff --git a/exporter/kafkaexporter/jaeger_marshaler.go b/exporter/kafkaexporter/jaeger_marshaler.go index d6d6beb643c3..50640c83763f 100644 --- a/exporter/kafkaexporter/jaeger_marshaler.go +++ b/exporter/kafkaexporter/jaeger_marshaler.go @@ -55,8 +55,7 @@ type jaegerSpanMarshaler interface { encoding() string } -type jaegerProtoSpanMarshaler struct { -} +type jaegerProtoSpanMarshaler struct{} var _ jaegerSpanMarshaler = (*jaegerProtoSpanMarshaler)(nil) diff --git a/exporter/kafkaexporter/pdata_marshaler.go b/exporter/kafkaexporter/pdata_marshaler.go index e67c4bcef35b..ae9726f2cbe8 100644 --- a/exporter/kafkaexporter/pdata_marshaler.go +++ b/exporter/kafkaexporter/pdata_marshaler.go @@ -27,7 +27,7 @@ func (p pdataLogsMarshaler) Marshal(ld plog.Logs, topic string) ([]*sarama.Produ for i := 0; i < logs.Len(); i++ { resourceMetrics := logs.At(i) - var hash = pdatautil.MapHash(resourceMetrics.Resource().Attributes()) + hash := pdatautil.MapHash(resourceMetrics.Resource().Attributes()) newLogs := plog.NewLogs() resourceMetrics.CopyTo(newLogs.ResourceLogs().AppendEmpty()) @@ -80,7 +80,7 @@ func (p pdataMetricsMarshaler) Marshal(ld pmetric.Metrics, topic string) ([]*sar for i := 0; i < metrics.Len(); i++ { resourceMetrics := metrics.At(i) - var hash = pdatautil.MapHash(resourceMetrics.Resource().Attributes()) + hash := pdatautil.MapHash(resourceMetrics.Resource().Attributes()) newMetrics := pmetric.NewMetrics() resourceMetrics.CopyTo(newMetrics.ResourceMetrics().AppendEmpty()) diff --git a/exporter/kafkaexporter/raw_marshaler.go b/exporter/kafkaexporter/raw_marshaler.go index 166be57f3e06..5a9e283436e8 100644 --- a/exporter/kafkaexporter/raw_marshaler.go +++ b/exporter/kafkaexporter/raw_marshaler.go @@ -14,8 +14,7 @@ import ( var errUnsupported = errors.New("unsupported serialization") -type rawMarshaler struct { -} +type rawMarshaler struct{} func newRawMarshaler() rawMarshaler { return rawMarshaler{} diff --git a/exporter/kineticaexporter/common.go b/exporter/kineticaexporter/common.go index 222c3b010ad2..6eb68b73463c 100644 --- a/exporter/kineticaexporter/common.go +++ b/exporter/kineticaexporter/common.go @@ -741,7 +741,7 @@ func getAttributeValue(vtPair ValueTypePair) (*AttributeValue, error) { // @param chunkSize // @return [][]T func chunkBySize[T any](items []T, chunkSize int) [][]T { - var _chunks = make([][]T, 0, (len(items)/chunkSize)+1) + _chunks := make([][]T, 0, (len(items)/chunkSize)+1) for chunkSize < len(items) { items, _chunks = items[chunkSize:], append(_chunks, items[0:chunkSize:chunkSize]) } diff --git a/exporter/kineticaexporter/config_test.go b/exporter/kineticaexporter/config_test.go index 997ea5b5dbf4..d4726fe36970 100644 --- a/exporter/kineticaexporter/config_test.go +++ b/exporter/kineticaexporter/config_test.go @@ -27,7 +27,6 @@ func TestLoadConfig(t *testing.T) { id component.ID expected component.Config }{ - { id: component.MustNewIDWithName("kinetica", ""), expected: defaultCfg, diff --git a/exporter/kineticaexporter/exporter_metric_test.go b/exporter/kineticaexporter/exporter_metric_test.go index 920e602d85f5..cca7713a38a3 100644 --- a/exporter/kineticaexporter/exporter_metric_test.go +++ b/exporter/kineticaexporter/exporter_metric_test.go @@ -20,15 +20,19 @@ import ( "go.uber.org/zap/zaptest" ) -var testServer *httptest.Server -var baseURL string - -var showTableMetricSummaryResponse = "\x04OK\x00&show_table_response\xfe\x13&otel.metric_summary\x02&otel.metric_summary\x00\x02\x00\x00\x02(14940230562727554683\x00\x02\xc6\x03{\"type\":\"record\",\"name\":\"type_name\",\"fields\":[{\"name\":\"summary_id\",\"type\":\"string\"},{\"name\":\"metric_name\",\"type\":\"string\"},{\"name\":\"metric_description\",\"type\":[\"string\",\"null\"]},{\"name\":\"metric_unit\",\"type\":[\"string\",\"null\"]}]}\x00\x02\x00\x00\x02\x08$metric_description\x06\x08data\x0echar256\x10nullable\x00\x16metric_name\x04\x08data\x0echar256\x00\x16metric_unit\x06\x08data\x0echar256\x10nullable\x00\x14summary_id\x08\x08data\x16primary_key\x12shard_key\x08uuid\x00\x00\x00\x028\"attribute_indexes\x00 collection_names\x08otel$compressed_columns\x000datasource_subscriptions\x00\x18foreign_keys\x00\"foreign_shard_key\x00$global_access_mode\x14read_write,is_automatic_partition\nfalse\x10is_dirty\x00\"is_view_persisted\x00\"last_refresh_time\x00(owner_resource_group= maxBodySize-2 { str := b.String() str = str[:len(str)-1] + "]}" diff --git a/exporter/mezmoexporter/exporter_test.go b/exporter/mezmoexporter/exporter_test.go index 868cdf8153bf..01588285c6dd 100644 --- a/exporter/mezmoexporter/exporter_test.go +++ b/exporter/mezmoexporter/exporter_test.go @@ -74,8 +74,8 @@ func createMaxLogData() plog.Logs { rl.ScopeLogs().AppendEmpty() // Add an empty ScopeLogs sl := rl.ScopeLogs().AppendEmpty() - var lineLen = maxMessageSize - var lineCnt = (maxBodySize / lineLen) * 2 + lineLen := maxMessageSize + lineCnt := (maxBodySize / lineLen) * 2 for i := 0; i < lineCnt; i++ { ts := pcommon.Timestamp(int64(i) * time.Millisecond.Nanoseconds()) @@ -109,11 +109,13 @@ type testServer struct { url string } -type httpAssertionCallback func(req *http.Request, body mezmoLogBody) (int, string) -type testServerParams struct { - t *testing.T - assertionsCallback httpAssertionCallback -} +type ( + httpAssertionCallback func(req *http.Request, body mezmoLogBody) (int, string) + testServerParams struct { + t *testing.T + assertionsCallback httpAssertionCallback + } +) // Creates an HTTP server to test log delivery payloads by applying a set of // assertions through the assertCB function. @@ -185,19 +187,19 @@ func TestLogsExporter(t *testing.T) { exporter := createExporter(t, config, log) t.Run("Test simple log data", func(t *testing.T) { - var logs = createSimpleLogData(3) + logs := createSimpleLogData(3) err := exporter.pushLogData(context.Background(), logs) require.NoError(t, err) }) t.Run("Test max message size", func(t *testing.T) { - var logs = createSizedPayloadLogData(maxMessageSize) + logs := createSizedPayloadLogData(maxMessageSize) err := exporter.pushLogData(context.Background(), logs) require.NoError(t, err) }) t.Run("Test max body size", func(t *testing.T) { - var logs = createMaxLogData() + logs := createMaxLogData() err := exporter.pushLogData(context.Background(), logs) require.NoError(t, err) }) diff --git a/exporter/mezmoexporter/factory_test.go b/exporter/mezmoexporter/factory_test.go index f08a3b34f4f3..77518c4cd371 100644 --- a/exporter/mezmoexporter/factory_test.go +++ b/exporter/mezmoexporter/factory_test.go @@ -26,10 +26,12 @@ func TestType(t *testing.T) { assert.Equal(t, pType, metadata.Type) } -var defaultMaxIdleConns = http.DefaultTransport.(*http.Transport).MaxIdleConns -var defaultMaxIdleConnsPerHost = http.DefaultTransport.(*http.Transport).MaxIdleConnsPerHost -var defaultMaxConnsPerHost = http.DefaultTransport.(*http.Transport).MaxConnsPerHost -var defaultIdleConnTimeout = http.DefaultTransport.(*http.Transport).IdleConnTimeout +var ( + defaultMaxIdleConns = http.DefaultTransport.(*http.Transport).MaxIdleConns + defaultMaxIdleConnsPerHost = http.DefaultTransport.(*http.Transport).MaxIdleConnsPerHost + defaultMaxConnsPerHost = http.DefaultTransport.(*http.Transport).MaxConnsPerHost + defaultIdleConnTimeout = http.DefaultTransport.(*http.Transport).IdleConnTimeout +) func TestCreateDefaultConfig(t *testing.T) { factory := NewFactory() diff --git a/exporter/mezmoexporter/utils_test.go b/exporter/mezmoexporter/utils_test.go index c8d6b860334f..1b5e6d96082d 100644 --- a/exporter/mezmoexporter/utils_test.go +++ b/exporter/mezmoexporter/utils_test.go @@ -40,7 +40,7 @@ func TestTruncateString(t *testing.T) { func TestRandString(t *testing.T) { t.Run("Test fixed length string", func(t *testing.T) { - var s = randString(16 * 1024) + s := randString(16 * 1024) require.Len(t, s, 16*1024) }) } diff --git a/exporter/opensearchexporter/encoder.go b/exporter/opensearchexporter/encoder.go index bc64ea1e9916..ec9696fed249 100644 --- a/exporter/opensearchexporter/encoder.go +++ b/exporter/opensearchexporter/encoder.go @@ -42,7 +42,8 @@ type encodeModel struct { func (m *encodeModel) encodeLog(resource pcommon.Resource, scope pcommon.InstrumentationScope, schemaURL string, - record plog.LogRecord) ([]byte, error) { + record plog.LogRecord, +) ([]byte, error) { if m.sso { return m.encodeLogSSO(resource, scope, schemaURL, record) } diff --git a/exporter/opensearchexporter/integration_test.go b/exporter/opensearchexporter/integration_test.go index cca19132e1ac..06227c2d6a13 100644 --- a/exporter/opensearchexporter/integration_test.go +++ b/exporter/opensearchexporter/integration_test.go @@ -109,7 +109,7 @@ func TestOpenSearchTraceExporter(t *testing.T) { for _, tc := range tests { // Create HTTP listener - var requestCount = 0 + requestCount := 0 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var err error docs := getReceivedDocuments(r.Body) @@ -239,7 +239,7 @@ func TestOpenSearchLogExporter(t *testing.T) { for _, tc := range tests { // Create HTTP listener - var requestCount = 0 + requestCount := 0 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var err error docs := getReceivedDocuments(r.Body) diff --git a/exporter/opensearchexporter/internal/objmodel/objmodel.go b/exporter/opensearchexporter/internal/objmodel/objmodel.go index efccbdc9f59e..de7d93da9b04 100644 --- a/exporter/opensearchexporter/internal/objmodel/objmodel.go +++ b/exporter/opensearchexporter/internal/objmodel/objmodel.go @@ -85,8 +85,10 @@ const ( const tsLayout = "2006-01-02T15:04:05.000000000Z" -var nilValue = Value{kind: KindNil} -var ignoreValue = Value{kind: KindIgnore} +var ( + nilValue = Value{kind: KindNil} + ignoreValue = Value{kind: KindIgnore} +) // DocumentFromAttributes creates a document from a OpenTelemetry attribute // map. All nested maps will be flattened, with keys being joined using a `.` symbol. diff --git a/exporter/opensearchexporter/trace_bulk_indexer.go b/exporter/opensearchexporter/trace_bulk_indexer.go index b6e7f5132e1e..4e7bcccc8a86 100644 --- a/exporter/opensearchexporter/trace_bulk_indexer.go +++ b/exporter/opensearchexporter/trace_bulk_indexer.go @@ -128,7 +128,7 @@ func attributesToMapString(attributes pcommon.Map) map[string]string { } func shouldRetryEvent(status int) bool { - var retryOnStatus = []int{500, 502, 503, 504, 429} + retryOnStatus := []int{500, 502, 503, 504, 429} for _, retryable := range retryOnStatus { if status == retryable { return true diff --git a/exporter/otelarrowexporter/internal/arrow/common_test.go b/exporter/otelarrowexporter/internal/arrow/common_test.go index 8c2bda7a59e7..a0451e7143c0 100644 --- a/exporter/otelarrowexporter/internal/arrow/common_test.go +++ b/exporter/otelarrowexporter/internal/arrow/common_test.go @@ -51,8 +51,10 @@ type commonTestCase struct { type noisyTest bool -const Noisy noisyTest = true -const NotNoisy noisyTest = false +const ( + Noisy noisyTest = true + NotNoisy noisyTest = false +) func newTestTelemetry(t zaptest.TestingT, noisy noisyTest) (component.TelemetrySettings, *observer.ObservedLogs) { telset := componenttest.NewNopTelemetrySettings() @@ -279,8 +281,7 @@ func (tc *unresponsiveTestChannel) unblock() { // unsupportedTestChannel mimics gRPC's behavior when there is no // arrow stream service registered with the server. -type arrowUnsupportedTestChannel struct { -} +type arrowUnsupportedTestChannel struct{} func newArrowUnsupportedTestChannel() *arrowUnsupportedTestChannel { return &arrowUnsupportedTestChannel{} @@ -314,8 +315,7 @@ func (tc *arrowUnsupportedTestChannel) onRecv(_ context.Context) func() (*arrowp } // disconnectedTestChannel allows the connection to time out. -type disconnectedTestChannel struct { -} +type disconnectedTestChannel struct{} func newDisconnectedTestChannel() *disconnectedTestChannel { return &disconnectedTestChannel{} @@ -383,8 +383,7 @@ func (tc *sendErrorTestChannel) onRecv(_ context.Context) func() (*arrowpb.Batch } // connectErrorTestChannel returns an error from the ArrowTraces() call -type connectErrorTestChannel struct { -} +type connectErrorTestChannel struct{} func newConnectErrorTestChannel() *connectErrorTestChannel { return &connectErrorTestChannel{} diff --git a/exporter/otelarrowexporter/internal/arrow/exporter_test.go b/exporter/otelarrowexporter/internal/arrow/exporter_test.go index b722df561ddd..e03e1b145aef 100644 --- a/exporter/otelarrowexporter/internal/arrow/exporter_test.go +++ b/exporter/otelarrowexporter/internal/arrow/exporter_test.go @@ -41,9 +41,11 @@ var AllPrioritizers = []PrioritizerName{LeastLoadedPrioritizer, LeastLoadedTwoPr const defaultMaxStreamLifetime = 11 * time.Second -type compareJSONTraces struct{ ptrace.Traces } -type compareJSONMetrics struct{ pmetric.Metrics } -type compareJSONLogs struct{ plog.Logs } +type ( + compareJSONTraces struct{ ptrace.Traces } + compareJSONMetrics struct{ pmetric.Metrics } + compareJSONLogs struct{ plog.Logs } +) func (c compareJSONTraces) MarshalJSON() ([]byte, error) { var m ptrace.JSONMarshaler diff --git a/exporter/otelarrowexporter/metadata.go b/exporter/otelarrowexporter/metadata.go index 1d24bfc6cb81..6bd167624dfc 100644 --- a/exporter/otelarrowexporter/metadata.go +++ b/exporter/otelarrowexporter/metadata.go @@ -28,10 +28,8 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/internal/otelarrow/netstats" ) -var ( - // errTooManyExporters is returned when the MetadataCardinalityLimit has been reached. - errTooManyExporters = consumererror.NewPermanent(errors.New("too many exporter metadata-value combinations")) -) +// errTooManyExporters is returned when the MetadataCardinalityLimit has been reached. +var errTooManyExporters = consumererror.NewPermanent(errors.New("too many exporter metadata-value combinations")) type metadataExporter struct { config *Config diff --git a/exporter/prometheusexporter/collector.go b/exporter/prometheusexporter/collector.go index 42035add2fbc..dd3891095473 100644 --- a/exporter/prometheusexporter/collector.go +++ b/exporter/prometheusexporter/collector.go @@ -22,9 +22,7 @@ import ( prometheustranslator "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/translator/prometheus" ) -var ( - separatorString = string([]byte{model.SeparatorByte}) -) +var separatorString = string([]byte{model.SeparatorByte}) type collector struct { accumulator accumulator diff --git a/exporter/prometheusexporter/collector_test.go b/exporter/prometheusexporter/collector_test.go index f1b87d9fe10b..0552f2ec7135 100644 --- a/exporter/prometheusexporter/collector_test.go +++ b/exporter/prometheusexporter/collector_test.go @@ -220,7 +220,6 @@ func TestConvertDoubleHistogramExemplar(t *testing.T) { pMap := pcommon.NewMap() c := collector{ - accumulator: &mockAccumulator{ metrics: []pmetric.Metric{metric}, resourceAttributes: pMap, @@ -262,7 +261,6 @@ func TestConvertMonotonicSumExemplar(t *testing.T) { pMap := pcommon.NewMap() c := collector{ - accumulator: &mockAccumulator{ metrics: []pmetric.Metric{metric}, resourceAttributes: pMap, @@ -295,6 +293,7 @@ func (c *errorCheckCore) Check(ent zapcore.Entry, ce *zapcore.CheckedEntry) *zap } return ce } + func (c *errorCheckCore) Write(ent zapcore.Entry, _ []zapcore.Field) error { if ent.Level == zapcore.ErrorLevel { c.errorMessages = append(c.errorMessages, ent.Message) diff --git a/exporter/prometheusexporter/end_to_end_test.go b/exporter/prometheusexporter/end_to_end_test.go index c9ff88437140..f3d1b70899a4 100644 --- a/exporter/prometheusexporter/end_to_end_test.go +++ b/exporter/prometheusexporter/end_to_end_test.go @@ -33,7 +33,7 @@ func TestEndToEndSummarySupport(t *testing.T) { // 1. Create the Prometheus scrape endpoint. var wg sync.WaitGroup - var currentScrapeIndex = 0 + currentScrapeIndex := 0 wg.Add(1) // scrape one endpoint dropWizardServer := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { diff --git a/exporter/prometheusremotewriteexporter/exporter_test.go b/exporter/prometheusremotewriteexporter/exporter_test.go index a61a4474e842..5fbe3ef237ab 100644 --- a/exporter/prometheusremotewriteexporter/exporter_test.go +++ b/exporter/prometheusremotewriteexporter/exporter_test.go @@ -292,7 +292,8 @@ func Test_export(t *testing.T) { httpResponseCode int returnErrorOnCreate bool }{ - {"success_case", + { + "success_case", *ts1, true, http.StatusAccepted, @@ -304,7 +305,8 @@ func Test_export(t *testing.T) { false, http.StatusAccepted, true, - }, { + }, + { "error_status_code_case", *ts1, true, @@ -807,32 +809,38 @@ func Test_validateAndSanitizeExternalLabels(t *testing.T) { expectedLabels map[string]string returnErrorOnCreate bool }{ - {"success_case_no_labels", + { + "success_case_no_labels", map[string]string{}, map[string]string{}, false, }, - {"success_case_with_labels", + { + "success_case_with_labels", map[string]string{"key1": "val1"}, map[string]string{"key1": "val1"}, false, }, - {"success_case_2_with_labels", + { + "success_case_2_with_labels", map[string]string{"__key1__": "val1"}, map[string]string{"__key1__": "val1"}, false, }, - {"success_case_with_sanitized_labels", + { + "success_case_with_sanitized_labels", map[string]string{"__key1.key__": "val1"}, map[string]string{"__key1_key__": "val1"}, false, }, - {"labels_that_start_with_digit", + { + "labels_that_start_with_digit", map[string]string{"6key_": "val1"}, map[string]string{"key_6key_": "val1"}, false, }, - {"fail_case_empty_label", + { + "fail_case_empty_label", map[string]string{"": "val1"}, map[string]string{}, true, @@ -844,32 +852,38 @@ func Test_validateAndSanitizeExternalLabels(t *testing.T) { expectedLabels map[string]string returnErrorOnCreate bool }{ - {"success_case_no_labels", + { + "success_case_no_labels", map[string]string{}, map[string]string{}, false, }, - {"success_case_with_labels", + { + "success_case_with_labels", map[string]string{"key1": "val1"}, map[string]string{"key1": "val1"}, false, }, - {"success_case_2_with_labels", + { + "success_case_2_with_labels", map[string]string{"__key1__": "val1"}, map[string]string{"__key1__": "val1"}, false, }, - {"success_case_with_sanitized_labels", + { + "success_case_with_sanitized_labels", map[string]string{"__key1.key__": "val1"}, map[string]string{"__key1_key__": "val1"}, false, }, - {"labels_that_start_with_digit", + { + "labels_that_start_with_digit", map[string]string{"6key_": "val1"}, map[string]string{"key_6key_": "val1"}, false, }, - {"fail_case_empty_label", + { + "fail_case_empty_label", map[string]string{"": "val1"}, map[string]string{}, true, diff --git a/exporter/prometheusremotewriteexporter/factory.go b/exporter/prometheusremotewriteexporter/factory.go index 7820c7e8d335..46c52d233d91 100644 --- a/exporter/prometheusremotewriteexporter/factory.go +++ b/exporter/prometheusremotewriteexporter/factory.go @@ -35,7 +35,8 @@ func NewFactory() exporter.Factory { } func createMetricsExporter(ctx context.Context, set exporter.Settings, - cfg component.Config) (exporter.Metrics, error) { + cfg component.Config, +) (exporter.Metrics, error) { prwCfg, ok := cfg.(*Config) if !ok { return nil, errors.New("invalid configuration") diff --git a/exporter/prometheusremotewriteexporter/factory_test.go b/exporter/prometheusremotewriteexporter/factory_test.go index fdcf8fbfdea8..8196d5baaf8f 100644 --- a/exporter/prometheusremotewriteexporter/factory_test.go +++ b/exporter/prometheusremotewriteexporter/factory_test.go @@ -44,25 +44,29 @@ func Test_createMetricsExporter(t *testing.T) { returnErrorOnCreate bool returnErrorOnStart bool }{ - {"success_case", + { + "success_case", createDefaultConfig(), exportertest.NewNopSettings(), false, false, }, - {"fail_case", + { + "fail_case", nil, exportertest.NewNopSettings(), true, false, }, - {"invalid_config_case", + { + "invalid_config_case", invalidConfig, exportertest.NewNopSettings(), true, false, }, - {"invalid_tls_config_case", + { + "invalid_tls_config_case", invalidTLSConfig, exportertest.NewNopSettings(), false, diff --git a/exporter/prometheusremotewriteexporter/testutil_test.go b/exporter/prometheusremotewriteexporter/testutil_test.go index eada2d8b30f6..02e1167164c3 100644 --- a/exporter/prometheusremotewriteexporter/testutil_test.go +++ b/exporter/prometheusremotewriteexporter/testutil_test.go @@ -321,7 +321,8 @@ func getExpHistogramMetric( } func getHistogramMetric(name string, attributes pcommon.Map, ts uint64, sum *float64, count uint64, bounds []float64, - buckets []uint64) pmetric.Metric { + buckets []uint64, +) pmetric.Metric { metric := pmetric.NewMetric() metric.SetName(name) metric.SetEmptyHistogram().SetAggregationTemporality(pmetric.AggregationTemporalityCumulative) diff --git a/exporter/pulsarexporter/jaeger_marshaler.go b/exporter/pulsarexporter/jaeger_marshaler.go index 786140d2c67d..26f7e449e5da 100644 --- a/exporter/pulsarexporter/jaeger_marshaler.go +++ b/exporter/pulsarexporter/jaeger_marshaler.go @@ -51,8 +51,7 @@ type jaegerBatchMarshaler interface { encoding() string } -type jaegerProtoBatchMarshaler struct { -} +type jaegerProtoBatchMarshaler struct{} var _ jaegerBatchMarshaler = (*jaegerProtoBatchMarshaler)(nil) diff --git a/exporter/pulsarexporter/pulsar_exporter.go b/exporter/pulsarexporter/pulsar_exporter.go index 1dba74d2fb21..6d3b8aea956f 100644 --- a/exporter/pulsarexporter/pulsar_exporter.go +++ b/exporter/pulsarexporter/pulsar_exporter.go @@ -162,7 +162,6 @@ func newPulsarProducer(config Config) (pulsar.Client, pulsar.Producer, error) { options := config.clientOptions() client, err := pulsar.NewClient(options) - if err != nil { return nil, nil, err } @@ -170,7 +169,6 @@ func newPulsarProducer(config Config) (pulsar.Client, pulsar.Producer, error) { producerOptions := config.getProducerOptions() producer, err := client.CreateProducer(producerOptions) - if err != nil { return nil, nil, err } diff --git a/exporter/pulsarexporter/pulsar_exporter_test.go b/exporter/pulsarexporter/pulsar_exporter_test.go index 795cd0754fdd..0d37c4602367 100644 --- a/exporter/pulsarexporter/pulsar_exporter_test.go +++ b/exporter/pulsarexporter/pulsar_exporter_test.go @@ -94,7 +94,6 @@ func (c *mockProducer) Send(context.Context, *pulsar.ProducerMessage) (pulsar.Me } func (c *mockProducer) SendAsync(context.Context, *pulsar.ProducerMessage, func(pulsar.MessageID, *pulsar.ProducerMessage, error)) { - } func (c *mockProducer) LastSequenceID() int64 { diff --git a/exporter/rabbitmqexporter/internal/publisher/publisher.go b/exporter/rabbitmqexporter/internal/publisher/publisher.go index 8a4ec63c688c..fa308b96b4fd 100644 --- a/exporter/rabbitmqexporter/internal/publisher/publisher.go +++ b/exporter/rabbitmqexporter/internal/publisher/publisher.go @@ -93,7 +93,6 @@ func (p *publisher) Publish(ctx context.Context, message Message) error { Body: message.Body, DeliveryMode: deliveryMode, }) - if err != nil { err = errors.Join(errors.New("error publishing message"), err) return err diff --git a/exporter/rabbitmqexporter/rabbitmq_exporter.go b/exporter/rabbitmqexporter/rabbitmq_exporter.go index d6f26d665d57..e7ae69ad8c3c 100644 --- a/exporter/rabbitmqexporter/rabbitmq_exporter.go +++ b/exporter/rabbitmqexporter/rabbitmq_exporter.go @@ -28,8 +28,10 @@ type rabbitmqExporter struct { publisher publisher.Publisher } -type publisherFactory = func(publisher.DialConfig) (publisher.Publisher, error) -type tlsFactory = func(context.Context) (*tls.Config, error) +type ( + publisherFactory = func(publisher.DialConfig) (publisher.Publisher, error) + tlsFactory = func(context.Context) (*tls.Config, error) +) func newRabbitmqExporter(cfg *Config, set component.TelemetrySettings, publisherFactory publisherFactory, tlsFactory tlsFactory, routingKey string, connectionName string) *rabbitmqExporter { exporter := &rabbitmqExporter{ diff --git a/exporter/rabbitmqexporter/rabbitmq_exporter_test.go b/exporter/rabbitmqexporter/rabbitmq_exporter_test.go index a5351c7c620d..76a9444ea0e7 100644 --- a/exporter/rabbitmqexporter/rabbitmq_exporter_test.go +++ b/exporter/rabbitmqexporter/rabbitmq_exporter_test.go @@ -29,7 +29,7 @@ func TestStartAndShutdown(t *testing.T) { factory := NewFactory() cfg := factory.CreateDefaultConfig().(*Config) pub := mockPublisher{} - var pubFactory = func(publisher.DialConfig) (publisher.Publisher, error) { + pubFactory := func(publisher.DialConfig) (publisher.Publisher, error) { return &pub, nil } exporter := newRabbitmqExporter(cfg, exportertest.NewNopSettings().TelemetrySettings, pubFactory, newTLSFactory(cfg), routingKey, connectionName) @@ -48,7 +48,7 @@ func TestStart_UnknownMarshallerEncoding(t *testing.T) { factory := NewFactory() cfg := factory.CreateDefaultConfig().(*Config) pub := mockPublisher{} - var pubFactory = func(publisher.DialConfig) (publisher.Publisher, error) { + pubFactory := func(publisher.DialConfig) (publisher.Publisher, error) { return &pub, nil } @@ -66,7 +66,7 @@ func TestStart_UnknownMarshallerEncoding(t *testing.T) { func TestStart_PublisherCreationErr(t *testing.T) { factory := NewFactory() cfg := factory.CreateDefaultConfig().(*Config) - var pubFactory = func(publisher.DialConfig) (publisher.Publisher, error) { + pubFactory := func(publisher.DialConfig) (publisher.Publisher, error) { return nil, errors.New("simulating error creating publisher") } exporter := newRabbitmqExporter(cfg, exportertest.NewNopSettings().TelemetrySettings, pubFactory, newTLSFactory(cfg), routingKey, connectionName) @@ -82,7 +82,7 @@ func TestStart_TLSError(t *testing.T) { factory := NewFactory() cfg := factory.CreateDefaultConfig().(*Config) pub := mockPublisher{} - var pubFactory = func(publisher.DialConfig) (publisher.Publisher, error) { + pubFactory := func(publisher.DialConfig) (publisher.Publisher, error) { return &pub, nil } tlsFactory := func(context.Context) (*tls.Config, error) { @@ -137,7 +137,7 @@ func exporterForPublishing(t *testing.T) (*mockPublisher, *rabbitmqExporter) { factory := NewFactory() cfg := factory.CreateDefaultConfig().(*Config) pub := mockPublisher{} - var pubFactory = func(publisher.DialConfig) (publisher.Publisher, error) { + pubFactory := func(publisher.DialConfig) (publisher.Publisher, error) { return &pub, nil } exporter := newRabbitmqExporter(cfg, exportertest.NewNopSettings().TelemetrySettings, pubFactory, newTLSFactory(cfg), routingKey, connectionName) diff --git a/exporter/sapmexporter/config.go b/exporter/sapmexporter/config.go index b1f7993bcda8..90107d461f95 100644 --- a/exporter/sapmexporter/config.go +++ b/exporter/sapmexporter/config.go @@ -22,7 +22,6 @@ const ( // Config defines configuration for SAPM exporter. type Config struct { - // Endpoint is the destination to where traces will be sent to in SAPM format. // It must be a full URL and include the scheme, port and path e.g, https://ingest.signalfx.com/v2/trace Endpoint string `mapstructure:"endpoint"` diff --git a/exporter/signalfxexporter/dpclient.go b/exporter/signalfxexporter/dpclient.go index 27987171b854..cdb7338c1bf8 100644 --- a/exporter/signalfxexporter/dpclient.go +++ b/exporter/signalfxexporter/dpclient.go @@ -244,7 +244,6 @@ func (s *sfxDPClient) pushOTLPMetricsDataForToken(ctx context.Context, mh pmetri s.logger.Debug("Sending metrics in OTLP format") err = s.postData(ctx, body, headers) - if err != nil { return dataPointCount, consumererror.NewMetrics(err, mh) } @@ -256,7 +255,6 @@ func (s *sfxDPClient) encodeOTLPBody(md pmetric.Metrics) (bodyReader io.Reader, tr := pmetricotlp.NewExportRequestFromMetrics(md) body, err := tr.MarshalProto() - if err != nil { return nil, false, err } diff --git a/exporter/signalfxexporter/exporter.go b/exporter/signalfxexporter/exporter.go index 0fc908c149d4..eaa3fa361aa7 100644 --- a/exporter/signalfxexporter/exporter.go +++ b/exporter/signalfxexporter/exporter.go @@ -25,9 +25,7 @@ import ( metadata "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/experimentalmetricmetadata" ) -var ( - errNotStarted = errors.New("exporter has not started") -) +var errNotStarted = errors.New("exporter has not started") // TODO: Find a place for this to be shared. type baseMetricsExporter struct { diff --git a/exporter/signalfxexporter/factory.go b/exporter/signalfxexporter/factory.go index 35c5428bb6af..65a3d891371e 100644 --- a/exporter/signalfxexporter/factory.go +++ b/exporter/signalfxexporter/factory.go @@ -133,7 +133,6 @@ func createMetricsExporter( exporterhelper.WithQueue(cfg.QueueSettings), exporterhelper.WithStart(exp.start), exporterhelper.WithShutdown(exp.shutdown)) - if err != nil { return nil, err } @@ -175,7 +174,6 @@ func createLogsExporter( exporterhelper.WithRetry(expCfg.BackOffConfig), exporterhelper.WithQueue(expCfg.QueueSettings), exporterhelper.WithStart(exp.startLogs)) - if err != nil { return nil, err } diff --git a/exporter/signalfxexporter/internal/apm/correlations/client.go b/exporter/signalfxexporter/internal/apm/correlations/client.go index ba86baf9a6c2..95f418ee01ff 100644 --- a/exporter/signalfxexporter/internal/apm/correlations/client.go +++ b/exporter/signalfxexporter/internal/apm/correlations/client.go @@ -21,10 +21,12 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/signalfxexporter/internal/apm/requests/requestcounter" ) -var ErrChFull = errors.New("request channel full") -var errRetryChFull = errors.New("retry channel full") -var errMaxAttempts = errors.New("maximum attempts exceeded") -var errRequestCancelled = errors.New("request cancelled") +var ( + ErrChFull = errors.New("request channel full") + errRetryChFull = errors.New("retry channel full") + errMaxAttempts = errors.New("maximum attempts exceeded") + errRequestCancelled = errors.New("request cancelled") +) // ErrMaxEntries is an error returned when the correlation endpoint returns a 418 http status // code indicating that the set of services or environments is too large to add another value @@ -199,7 +201,8 @@ func (cc *Client) Correlate(cor *Correlation, cb CorrelateCB) { cor.Logger(cc.log).WithError(err).WithFields(log.Fields{"method": http.MethodPut}).Error("Unable to update dimension, not retrying") } cb(cor, err) - }}) + }, + }) if err != nil { cor.Logger(cc.log).WithError(err).WithFields(log.Fields{"method": http.MethodPut}).Debug("Unable to update dimension, not retrying") } @@ -223,7 +226,8 @@ func (cc *Client) Delete(cor *Correlation, callback SuccessfulDeleteCB) { default: cc.log.WithError(err).Error("Unable to update dimension, not retrying") } - }}) + }, + }) if err != nil { cor.Logger(cc.log).WithError(err).WithFields(log.Fields{"method": http.MethodDelete}).Debug("Unable to update dimension, not retrying") } @@ -243,7 +247,7 @@ func (cc *Client) Get(dimName string, dimValue string, callback SuccessfulGetCB) callback: func(body []byte, statuscode int, err error) { switch statuscode { case http.StatusOK: - var response = map[string][]string{} + response := map[string][]string{} err = json.Unmarshal(body, &response) if err != nil { cc.log.WithError(err).WithFields(log.Fields{"dim": dimName, "value": dimValue}).Error("Unable to unmarshall correlations for dimension") diff --git a/exporter/signalfxexporter/internal/apm/correlations/client_test.go b/exporter/signalfxexporter/internal/apm/correlations/client_test.go index 023ddbbe9320..95d737f280f3 100644 --- a/exporter/signalfxexporter/internal/apm/correlations/client_test.go +++ b/exporter/signalfxexporter/internal/apm/correlations/client_test.go @@ -24,9 +24,11 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/signalfxexporter/internal/apm/log" ) -var getPathRegexp = regexp.MustCompile(`/v2/apm/correlate/([^/]+)/([^/]+)`) // /dimName/dimVal -var putPathRegexp = regexp.MustCompile(`/v2/apm/correlate/([^/]+)/([^/]+)/([^/]+)`) // /dimName/dimVal/{service,environment} -var deletePathRegexp = regexp.MustCompile(`/v2/apm/correlate/([^/]+)/([^/]+)/([^/]+)/([^/]+)`) // /dimName/dimValue/{service,environment}/value +var ( + getPathRegexp = regexp.MustCompile(`/v2/apm/correlate/([^/]+)/([^/]+)`) // /dimName/dimVal + putPathRegexp = regexp.MustCompile(`/v2/apm/correlate/([^/]+)/([^/]+)/([^/]+)`) // /dimName/dimVal/{service,environment} + deletePathRegexp = regexp.MustCompile(`/v2/apm/correlate/([^/]+)/([^/]+)/([^/]+)/([^/]+)`) // /dimName/dimValue/{service,environment}/value +) func waitForCors(corCh <-chan *request, count, waitSeconds int) []*request { // nolint: unparam cors := make([]*request, 0, count) diff --git a/exporter/signalfxexporter/internal/apm/correlations/dedup.go b/exporter/signalfxexporter/internal/apm/correlations/dedup.go index 2e5d7e9c0388..28e26dc483fe 100644 --- a/exporter/signalfxexporter/internal/apm/correlations/dedup.go +++ b/exporter/signalfxexporter/internal/apm/correlations/dedup.go @@ -21,7 +21,7 @@ type deduplicator struct { } func (d *deduplicator) purgeCreates() { - var elem = d.pendingCreates.Front() + elem := d.pendingCreates.Front() for { if elem == nil { return @@ -38,7 +38,7 @@ func (d *deduplicator) purgeCreates() { } func (d *deduplicator) purgeDeletes() { - var elem = d.pendingDeletes.Front() + elem := d.pendingDeletes.Front() for { if elem == nil { return @@ -60,7 +60,7 @@ func (d *deduplicator) purge() { } func (d *deduplicator) evictPendingDelete() { - var elem = d.pendingDeletes.Back() + elem := d.pendingDeletes.Back() if elem != nil { req, ok := elem.Value.(*request) if ok { @@ -72,7 +72,7 @@ func (d *deduplicator) evictPendingDelete() { } func (d *deduplicator) evictPendingCreate() { - var elem = d.pendingCreates.Back() + elem := d.pendingCreates.Back() if elem != nil { req, ok := elem.Value.(*request) if ok { diff --git a/exporter/signalfxexporter/internal/apm/log/log.go b/exporter/signalfxexporter/internal/apm/log/log.go index 0924d8ce955a..3709ddd5d72b 100644 --- a/exporter/signalfxexporter/internal/apm/log/log.go +++ b/exporter/signalfxexporter/internal/apm/log/log.go @@ -7,8 +7,7 @@ package log // import "github.com/open-telemetry/opentelemetry-collector-contrib // Fields is a map that is used to populated logging context. type Fields map[string]any -type nilLogger struct { -} +type nilLogger struct{} func (n nilLogger) Debug(string) { } diff --git a/exporter/signalfxexporter/internal/apm/requests/requestcounter/counter.go b/exporter/signalfxexporter/internal/apm/requests/requestcounter/counter.go index ca7d597eb426..bdadb51de0cb 100644 --- a/exporter/signalfxexporter/internal/apm/requests/requestcounter/counter.go +++ b/exporter/signalfxexporter/internal/apm/requests/requestcounter/counter.go @@ -17,9 +17,11 @@ const ( resetRequestCountKey key = 3 ) -type getRequestCount func() uint32 -type incrementRequestCount func() -type resetRequestCount func() +type ( + getRequestCount func() uint32 + incrementRequestCount func() + resetRequestCount func() +) // checks if a counter already exists on the context func counterExists(ctx context.Context) (exists bool) { diff --git a/exporter/signalfxexporter/internal/apm/requests/sender.go b/exporter/signalfxexporter/internal/apm/requests/sender.go index 708f00571655..93d691ff1167 100644 --- a/exporter/signalfxexporter/internal/apm/requests/sender.go +++ b/exporter/signalfxexporter/internal/apm/requests/sender.go @@ -99,11 +99,15 @@ func (rs *ReqSender) sendRequest(req *http.Request) error { type key int -const RequestFailedCallbackKey key = 1 -const RequestSuccessCallbackKey key = 2 +const ( + RequestFailedCallbackKey key = 1 + RequestSuccessCallbackKey key = 2 +) -type RequestFailedCallback func(body []byte, statusCode int, err error) -type RequestSuccessCallback func([]byte) +type ( + RequestFailedCallback func(body []byte, statusCode int, err error) + RequestSuccessCallback func([]byte) +) func onRequestSuccess(req *http.Request, body []byte) { ctx := req.Context() @@ -113,6 +117,7 @@ func onRequestSuccess(req *http.Request, body []byte) { } cb(body) } + func onRequestFailed(req *http.Request, body []byte, statusCode int, err error) { ctx := req.Context() cb, ok := ctx.Value(RequestFailedCallbackKey).(RequestFailedCallback) @@ -124,7 +129,6 @@ func onRequestFailed(req *http.Request, body []byte, statusCode int, err error) func sendRequest(client *http.Client, req *http.Request) ([]byte, int, error) { resp, err := client.Do(req) - if err != nil { return nil, 0, err } diff --git a/exporter/signalfxexporter/internal/apm/tracetracker/tracker_test.go b/exporter/signalfxexporter/internal/apm/tracetracker/tracker_test.go index 6b69551abfa1..24a366de1727 100644 --- a/exporter/signalfxexporter/internal/apm/tracetracker/tracker_test.go +++ b/exporter/signalfxexporter/internal/apm/tracetracker/tracker_test.go @@ -96,6 +96,7 @@ func (c *correlationTestClient) Get(_ string, dimValue string, cb correlations.S } }() } + func (c *correlationTestClient) Correlate(cl *correlations.Correlation, cb correlations.CorrelateCB) { c.Lock() defer c.Unlock() @@ -103,6 +104,7 @@ func (c *correlationTestClient) Correlate(cl *correlations.Correlation, cb corre cb(cl, nil) atomic.AddInt64(&c.correlateCounter, 1) } + func (c *correlationTestClient) Delete(cl *correlations.Correlation, cb correlations.SuccessfulDeleteCB) { c.Lock() defer c.Unlock() @@ -110,6 +112,7 @@ func (c *correlationTestClient) Delete(cl *correlations.Correlation, cb correlat cb(cl) atomic.AddInt64(&c.deleteCounter, 1) } + func (c *correlationTestClient) getCorrelations() []*correlations.Correlation { c.Lock() defer c.Unlock() diff --git a/exporter/signalfxexporter/internal/correlation/correlation.go b/exporter/signalfxexporter/internal/correlation/correlation.go index eb2df4fb27b0..5b3ac9c66fde 100644 --- a/exporter/signalfxexporter/internal/correlation/correlation.go +++ b/exporter/signalfxexporter/internal/correlation/correlation.go @@ -68,7 +68,6 @@ func newCorrelationClient(ctx context.Context, cfg *Config, accessToken configop AccessToken: string(accessToken), URL: corrURL, }) - if err != nil { cancel() return nil, fmt.Errorf("failed to create correlation client: %w", err) diff --git a/exporter/signalfxexporter/internal/dimensions/dimclient.go b/exporter/signalfxexporter/internal/dimensions/dimclient.go index ff0337767d3b..71e6dd00ca9a 100644 --- a/exporter/signalfxexporter/internal/dimensions/dimclient.go +++ b/exporter/signalfxexporter/internal/dimensions/dimclient.go @@ -230,7 +230,6 @@ func (dc *DimensionClient) handleDimensionUpdate(ctx context.Context, dimUpdate ) req, err = dc.makePatchRequest(ctx, dimUpdate) - if err != nil { return err } diff --git a/exporter/signalfxexporter/internal/dimensions/metadata.go b/exporter/signalfxexporter/internal/dimensions/metadata.go index 188fb4047872..9ccf16933abe 100644 --- a/exporter/signalfxexporter/internal/dimensions/metadata.go +++ b/exporter/signalfxexporter/internal/dimensions/metadata.go @@ -20,7 +20,8 @@ type MetadataUpdateClient interface { func getDimensionUpdateFromMetadata( metadata metadata.MetadataUpdate, - metricsConverter translation.MetricsConverter) *DimensionUpdate { + metricsConverter translation.MetricsConverter, +) *DimensionUpdate { properties, tags := getPropertiesAndTags(metadata) return &DimensionUpdate{ diff --git a/exporter/signalfxexporter/internal/dimensions/requests.go b/exporter/signalfxexporter/internal/dimensions/requests.go index f2f7277200fe..4722f063d0e6 100644 --- a/exporter/signalfxexporter/internal/dimensions/requests.go +++ b/exporter/signalfxexporter/internal/dimensions/requests.go @@ -22,7 +22,8 @@ type ReqSender struct { } func NewReqSender(client *http.Client, - workerCount uint, diagnosticDimensions map[string]string) *ReqSender { + workerCount uint, diagnosticDimensions map[string]string, +) *ReqSender { return &ReqSender{ client: client, additionalDimensions: diagnosticDimensions, @@ -94,11 +95,15 @@ func (rs *ReqSender) sendRequest(req *http.Request) error { type key int -const RequestFailedCallbackKey key = 1 -const RequestSuccessCallbackKey key = 2 +const ( + RequestFailedCallbackKey key = 1 + RequestSuccessCallbackKey key = 2 +) -type RequestFailedCallback func(statusCode int, err error) -type RequestSuccessCallback func([]byte) +type ( + RequestFailedCallback func(statusCode int, err error) + RequestSuccessCallback func([]byte) +) func onRequestSuccess(req *http.Request, body []byte) { ctx := req.Context() @@ -108,6 +113,7 @@ func onRequestSuccess(req *http.Request, body []byte) { } cb(body) } + func onRequestFailed(req *http.Request, statusCode int, err error) { ctx := req.Context() cb, ok := ctx.Value(RequestFailedCallbackKey).(RequestFailedCallback) @@ -119,7 +125,6 @@ func onRequestFailed(req *http.Request, statusCode int, err error) { func sendRequest(client *http.Client, req *http.Request) ([]byte, int, error) { resp, err := client.Do(req) - if err != nil { return nil, 0, err } diff --git a/exporter/signalfxexporter/internal/hostmetadata/host.go b/exporter/signalfxexporter/internal/hostmetadata/host.go index a9150b4a4c6c..2e9558f41800 100644 --- a/exporter/signalfxexporter/internal/hostmetadata/host.go +++ b/exporter/signalfxexporter/internal/hostmetadata/host.go @@ -32,10 +32,12 @@ var etcPath = func() string { const cpuStatsTimeout = 10 * time.Second // Map library functions to unexported package variables for testing purposes. -var cpuInfo = cpu.InfoWithContext -var cpuCounts = cpu.CountsWithContext -var memVirtualMemory = mem.VirtualMemory -var hostInfo = host.Info +var ( + cpuInfo = cpu.InfoWithContext + cpuCounts = cpu.CountsWithContext + memVirtualMemory = mem.VirtualMemory + hostInfo = host.Info +) // hostCPU information about the host type hostCPU struct { @@ -179,7 +181,7 @@ func getMemory() (*Memory, error) { func getStringFromFile(pattern string, path string) (string, error) { var err error var file []byte - var reg = regexp.MustCompile(pattern) + reg := regexp.MustCompile(pattern) if file, err = os.ReadFile(path); err == nil { if match := reg.FindSubmatch(file); len(match) > 1 { return string(match[1]), nil diff --git a/exporter/signalfxexporter/internal/hostmetadata/host_linux_test.go b/exporter/signalfxexporter/internal/hostmetadata/host_linux_test.go index 5b662cfdcdf1..6e90c1304f2a 100644 --- a/exporter/signalfxexporter/internal/hostmetadata/host_linux_test.go +++ b/exporter/signalfxexporter/internal/hostmetadata/host_linux_test.go @@ -32,11 +32,13 @@ func TestFillOSSpecificData(t *testing.T) { args: args{ etc: "./testdata/lsb-release", syscallUname: func(in *unix.Utsname) error { - in.Version = [65]byte{35, 57, 45, 85, 98, 117, 110, 116, + in.Version = [65]byte{ + 35, 57, 45, 85, 98, 117, 110, 116, 117, 32, 83, 77, 80, 32, 87, 101, 100, 32, 77, 97, 121, 32, 49, 54, 32, 49, 53, 58, 50, 50, 58, 53, 52, 32, 85, - 84, 67, 32, 50, 48, 49, 56} + 84, 67, 32, 50, 48, 49, 56, + } return nil }, }, diff --git a/exporter/signalfxexporter/internal/translation/converter.go b/exporter/signalfxexporter/internal/translation/converter.go index ffc5e91e1d18..27d1930fa51f 100644 --- a/exporter/signalfxexporter/internal/translation/converter.go +++ b/exporter/signalfxexporter/internal/translation/converter.go @@ -49,7 +49,8 @@ func NewMetricsConverter( includes []dpfilters.MetricFilter, nonAlphanumericDimChars string, dropHistogramBuckets bool, - processHistograms bool) (*MetricsConverter, error) { + processHistograms bool, +) (*MetricsConverter, error) { fs, err := dpfilters.NewFilterSet(excludes, includes) if err != nil { return nil, err diff --git a/exporter/signalfxexporter/internal/translation/dpfilters/filterset_test.go b/exporter/signalfxexporter/internal/translation/dpfilters/filterset_test.go index 64293030ee2c..4125c7f45335 100644 --- a/exporter/signalfxexporter/internal/translation/dpfilters/filterset_test.go +++ b/exporter/signalfxexporter/internal/translation/dpfilters/filterset_test.go @@ -101,7 +101,8 @@ func TestFilterSet(t *testing.T) { excludes: []MetricFilter{{ Dimensions: map[string]any{ "container_name": "PO", - }}}, + }, + }}, expectedMatches: []*sfxpb.DataPoint{ { Metric: "cpu.utilization", @@ -120,7 +121,8 @@ func TestFilterSet(t *testing.T) { excludes: []MetricFilter{{ Dimensions: map[string]any{ "container_name": []any{"PO"}, - }}}, + }, + }}, expectedMatches: []*sfxpb.DataPoint{ { Metric: "cpu.utilization", @@ -139,7 +141,8 @@ func TestFilterSet(t *testing.T) { excludes: []MetricFilter{{ Dimensions: map[string]any{ "container_name": []any{`/^[A-Z][A-Z]$/`}, - }}}, + }, + }}, expectedMatches: []*sfxpb.DataPoint{ { Metric: "cpu.utilization", @@ -158,7 +161,8 @@ func TestFilterSet(t *testing.T) { excludes: []MetricFilter{{ Dimensions: map[string]any{ "container_name": []any{`/.+/`}, - }}}, + }, + }}, expectedMatches: []*sfxpb.DataPoint{ { Metric: "cpu.utilization", @@ -177,7 +181,8 @@ func TestFilterSet(t *testing.T) { excludes: []MetricFilter{{ Dimensions: map[string]any{ "container_name": []any{`*O*`}, - }}}, + }, + }}, expectedMatches: []*sfxpb.DataPoint{ { Metric: "cpu.utilization", @@ -234,7 +239,8 @@ func TestFilterSet(t *testing.T) { excludes: []MetricFilter{{ Dimensions: map[string]any{ "container_name": []any{"mycontainer"}, - }}}, + }, + }}, expectedNonMatches: []*sfxpb.DataPoint{ { Metric: "cpu.utilization", @@ -247,7 +253,8 @@ func TestFilterSet(t *testing.T) { Dimensions: map[string]any{ "host": []any{"localhost"}, "system": []any{"r4"}, - }}}, + }, + }}, expectedNonMatches: []*sfxpb.DataPoint{ { Metric: "cpu.utilization", @@ -266,7 +273,8 @@ func TestFilterSet(t *testing.T) { Dimensions: map[string]any{ "host": []any{"localhost"}, "system": []any{"r4"}, - }}}, + }, + }}, expectedMatches: []*sfxpb.DataPoint{ { Metric: "cpu.utilization", @@ -282,7 +290,8 @@ func TestFilterSet(t *testing.T) { Dimensions: map[string]any{ "host": []any{"localhost"}, "system": []any{"r4"}, - }}}, + }, + }}, expectedMatches: []*sfxpb.DataPoint{ { Metric: "cpu.utilization", @@ -307,7 +316,8 @@ func TestFilterSet(t *testing.T) { excludes: []MetricFilter{{ Dimensions: map[string]any{ "container_name": []any{"*", "!pause", "!/.*idle/"}, - }}}, + }, + }}, expectedMatches: []*sfxpb.DataPoint{ { Metric: "cpu.utilization", @@ -345,7 +355,8 @@ func TestFilterSet(t *testing.T) { excludes: []MetricFilter{{ Dimensions: map[string]any{ "dim": []any{}, - }}}, + }, + }}, wantErr: true, wantErrMsg: "string map value in filter cannot be empty", }, @@ -360,7 +371,8 @@ func TestFilterSet(t *testing.T) { excludes: []MetricFilter{{ Dimensions: map[string]any{ "container_name": []any{"cpu.*["}, - }}}, + }, + }}, wantErr: true, wantErrMsg: "unexpected end of input", }, @@ -369,7 +381,8 @@ func TestFilterSet(t *testing.T) { excludes: []MetricFilter{{ Dimensions: map[string]any{ "host": 1, - }}}, + }, + }}, wantErr: true, wantErrMsg: "1 should be either a string or string list", }, diff --git a/exporter/signalfxexporter/internal/translation/dpfilters/string.go b/exporter/signalfxexporter/internal/translation/dpfilters/string.go index ee971708cd8f..093139ef8198 100644 --- a/exporter/signalfxexporter/internal/translation/dpfilters/string.go +++ b/exporter/signalfxexporter/internal/translation/dpfilters/string.go @@ -33,7 +33,6 @@ func NewStringFilter(items []string) (*StringFilter, error) { reText := stripSlashes(m) re, err = regexp.Compile(reText) - if err != nil { return nil, err } diff --git a/exporter/signalfxexporter/internal/translation/translator.go b/exporter/signalfxexporter/internal/translation/translator.go index 6c54e10c12f1..324188e820ee 100644 --- a/exporter/signalfxexporter/internal/translation/translator.go +++ b/exporter/signalfxexporter/internal/translation/translator.go @@ -748,7 +748,7 @@ func aggregateDatapoints( // generate map keys. func stringifyDimensions(dimensions []*sfxpb.Dimension, exclusions []string) string { const aggregationKeyDelimiter = "//" - var aggregationKeyParts = make([]string, 0, len(dimensions)) + aggregationKeyParts := make([]string, 0, len(dimensions)) for _, d := range dimensions { if !dimensionIn(d, exclusions) { aggregationKeyParts = append(aggregationKeyParts, fmt.Sprintf("%s:%s", d.Key, d.Value)) @@ -823,7 +823,7 @@ func convertMetricValue(logger *zap.Logger, dp *sfxpb.DataPoint, newType MetricV zap.String("metric", dp.Metric)) return } - var intVal = int64(*val) + intVal := int64(*val) dp.Value = sfxpb.Datum{IntValue: &intVal} case MetricValueTypeDouble: val := dp.GetValue().IntValue @@ -832,7 +832,7 @@ func convertMetricValue(logger *zap.Logger, dp *sfxpb.DataPoint, newType MetricV zap.String("metric", dp.Metric)) return } - var floatVal = float64(*val) + floatVal := float64(*val) dp.Value = sfxpb.Datum{DoubleValue: &floatVal} } } @@ -869,7 +869,8 @@ func dropDimensions(dp *sfxpb.DataPoint, rule Rule) { func filterDimensionsByValues( dimensions []*sfxpb.Dimension, - dimensionPairs map[string]map[string]bool) []*sfxpb.Dimension { + dimensionPairs map[string]map[string]bool, +) []*sfxpb.Dimension { if len(dimensions) == 0 { return nil } diff --git a/exporter/signalfxexporter/internal/translation/translator_test.go b/exporter/signalfxexporter/internal/translation/translator_test.go index 23e13981f9f0..23fa4194074f 100644 --- a/exporter/signalfxexporter/internal/translation/translator_test.go +++ b/exporter/signalfxexporter/internal/translation/translator_test.go @@ -553,8 +553,10 @@ func TestNewMetricTranslator(t *testing.T) { } } -var msec = time.Now().Unix() * 1e3 -var gaugeType = sfxpb.MetricType_GAUGE +var ( + msec = time.Now().Unix() * 1e3 + gaugeType = sfxpb.MetricType_GAUGE +) func TestTranslateDataPoints(t *testing.T) { tests := []struct { @@ -2395,12 +2397,12 @@ func TestCalculateNewMetric_Double(t *testing.T) { } func generateIntPtr(i int) *int64 { - var iPtr = int64(i) + iPtr := int64(i) return &iPtr } func generateFloatPtr(i float64) *float64 { - var iPtr = i + iPtr := i return &iPtr } @@ -2884,7 +2886,8 @@ func TestDropDimensions(t *testing.T) { }, }, }, - }, { + }, + { name: "No op when dimensions do not exist on dp", rules: []Rule{ { diff --git a/exporter/signalfxexporter/internal/utils/histogram_utils_test.go b/exporter/signalfxexporter/internal/utils/histogram_utils_test.go index 03d7f366a2c9..3a2426968ee3 100644 --- a/exporter/signalfxexporter/internal/utils/histogram_utils_test.go +++ b/exporter/signalfxexporter/internal/utils/histogram_utils_test.go @@ -220,7 +220,8 @@ func TestHistogramsAreRetrieved(t *testing.T) { ilm1.Metrics().AppendEmpty() buildHistogram(ilm1.Metrics().At(1), "histogram_2_s2", ts, 2) return out - }}, + }, + }, { name: "mixed_type_multiple_resources", inMetricsFunc: func() pmetric.Metrics { @@ -292,7 +293,8 @@ func TestHistogramsAreRetrieved(t *testing.T) { buildHistogram(ilm0r1.Metrics().At(0), "histogram_s0_r2", ts, 1) return out - }}, + }, + }, { name: "remove_access_token", inMetricsFunc: func() pmetric.Metrics { diff --git a/exporter/splunkhecexporter/buffer.go b/exporter/splunkhecexporter/buffer.go index 0a10a973783f..8c134043614b 100644 --- a/exporter/splunkhecexporter/buffer.go +++ b/exporter/splunkhecexporter/buffer.go @@ -11,9 +11,7 @@ import ( "sync" ) -var ( - errOverCapacity = errors.New("over capacity") -) +var errOverCapacity = errors.New("over capacity") type buffer interface { io.Writer diff --git a/exporter/splunkhecexporter/client.go b/exporter/splunkhecexporter/client.go index 8cf5747cd41f..70e2e11bb659 100644 --- a/exporter/splunkhecexporter/client.go +++ b/exporter/splunkhecexporter/client.go @@ -154,9 +154,11 @@ func (c *client) pushLogData(ctx context.Context, ld plog.Logs) error { // A guesstimated value > length of bytes of a single event. // Added to buffer capacity so that buffer is likely to grow by reslicing when buf.Len() > bufCap. -const bufCapPadding = uint(4096) -const libraryHeaderName = "X-Splunk-Instrumentation-Library" -const profilingLibraryName = "otel.profiling" +const ( + bufCapPadding = uint(4096) + libraryHeaderName = "X-Splunk-Instrumentation-Library" + profilingLibraryName = "otel.profiling" +) func isProfilingData(sl plog.ScopeLogs) bool { return sl.Scope().Name() == profilingLibraryName diff --git a/exporter/splunkhecexporter/client_test.go b/exporter/splunkhecexporter/client_test.go index 5cdaf73a90ae..0f4ccd1e349f 100644 --- a/exporter/splunkhecexporter/client_test.go +++ b/exporter/splunkhecexporter/client_test.go @@ -132,7 +132,7 @@ func createLogData(numResources int, numLibraries int, numRecords int) plog.Logs } func repeat(what int, times int) []int { - var result = make([]int, times) + result := make([]int, times) for i := range result { result[i] = what } @@ -397,10 +397,12 @@ func TestReceiveTracesBatches(t *testing.T) { }(), want: wantType{ batches: [][]string{ - {`"start_time":1`, + { + `"start_time":1`, `"start_time":2`, `start_time":3`, - `start_time":4`}, + `start_time":4`, + }, }, numBatches: 1, }, @@ -570,10 +572,12 @@ func TestReceiveLogs(t *testing.T) { }(), want: wantType{ batches: [][]string{ - {`"otel.log.name":"0_0_0"`, + { + `"otel.log.name":"0_0_0"`, `"otel.log.name":"0_0_1"`, `otel.log.name":"0_0_2`, - `otel.log.name":"0_0_3`}, + `otel.log.name":"0_0_3`, + }, }, numBatches: 1, }, diff --git a/exporter/splunkhecexporter/factory.go b/exporter/splunkhecexporter/factory.go index 8d806de5e7b5..a5d82775b28e 100644 --- a/exporter/splunkhecexporter/factory.go +++ b/exporter/splunkhecexporter/factory.go @@ -129,7 +129,6 @@ func createTracesExporter( exporterhelper.WithShutdown(c.stop), exporterhelper.WithBatcher(cfg.BatcherConfig), ) - if err != nil { return nil, err } @@ -198,7 +197,6 @@ func createLogsExporter( exporterhelper.WithShutdown(c.stop), exporterhelper.WithBatcher(cfg.BatcherConfig), ) - if err != nil { return nil, err } diff --git a/exporter/splunkhecexporter/integration_test.go b/exporter/splunkhecexporter/integration_test.go index d04d429136d0..288ffd2435d2 100644 --- a/exporter/splunkhecexporter/integration_test.go +++ b/exporter/splunkhecexporter/integration_test.go @@ -105,7 +105,7 @@ func startSplunk() SplunkContainerConfig { { HostFilePath: filepath.Join("testdata", "splunk.yaml"), ContainerFilePath: "/tmp/defaults/default.yml", - FileMode: 0644, + FileMode: 0o644, }, }, WaitingFor: wait.ForHealthCheck().WithStartupTimeout(5 * time.Minute), @@ -115,7 +115,6 @@ func startSplunk() SplunkContainerConfig { ContainerRequest: req, Started: true, }) - if err != nil { logger.Info("Error while creating container") panic(err) @@ -223,9 +222,11 @@ type cfg struct { type telemetryType string -var metricsType = telemetryType("metrics") -var logsType = telemetryType("logs") -var tracesType = telemetryType("traces") +var ( + metricsType = telemetryType("metrics") + logsType = telemetryType("logs") + tracesType = telemetryType("traces") +) type testCfg struct { name string diff --git a/exporter/splunkhecexporter/internal/integrationtestutils/config_helper.go b/exporter/splunkhecexporter/internal/integrationtestutils/config_helper.go index 651b52929714..86c0685e4c4d 100644 --- a/exporter/splunkhecexporter/internal/integrationtestutils/config_helper.go +++ b/exporter/splunkhecexporter/internal/integrationtestutils/config_helper.go @@ -102,7 +102,7 @@ func SetConfigVariable(key string, value string) { } // Write yaml file - err = os.WriteFile(configFilePth, newData, 0600) + err = os.WriteFile(configFilePth, newData, 0o600) if err != nil { fmt.Printf("Error writing file: %v", err) return diff --git a/exporter/splunkhecexporter/internal/integrationtestutils/splunk.go b/exporter/splunkhecexporter/internal/integrationtestutils/splunk.go index 2ef7f21d7b4d..36199d2abd4a 100644 --- a/exporter/splunkhecexporter/internal/integrationtestutils/splunk.go +++ b/exporter/splunkhecexporter/internal/integrationtestutils/splunk.go @@ -115,6 +115,7 @@ func checkSearchJobStatusCode(user string, password string, baseURL string, jobI logger.Printf("Is Splunk Search completed [isDone flag]: %v\n", isDone) return isDone } + func postSearchRequest(user string, password string, baseURL string, searchQuery string, startTime string, endTime string) string { logger := log.New(os.Stdout, "", log.LstdFlags) searchURL := fmt.Sprintf("%s/services/search/jobs?output_mode=json", baseURL) diff --git a/exporter/splunkhecexporter/tracedata_to_splunk_test.go b/exporter/splunkhecexporter/tracedata_to_splunk_test.go index 377970076f19..491d66147771 100644 --- a/exporter/splunkhecexporter/tracedata_to_splunk_test.go +++ b/exporter/splunkhecexporter/tracedata_to_splunk_test.go @@ -122,7 +122,8 @@ func commonSplunkEvent( Source: "myservice", SourceType: "mysourcetype", Index: "myindex", - Event: hecSpan{Name: name, StartTime: ts, + Event: hecSpan{ + Name: name, StartTime: ts, TraceID: "", SpanID: "", ParentSpan: "", diff --git a/exporter/sumologicexporter/sender.go b/exporter/sumologicexporter/sender.go index 8e8d0a82b9ce..d52cfcbcdb3f 100644 --- a/exporter/sumologicexporter/sender.go +++ b/exporter/sumologicexporter/sender.go @@ -354,7 +354,6 @@ func (s *sender) logToJSON(record plog.LogRecord) (string, error) { enc := json.NewEncoder(nextLine) enc.SetEscapeHTML(false) err := enc.Encode(recordCopy.Attributes().AsRaw()) - if err != nil { return "", err } @@ -700,6 +699,7 @@ func (s *sender) addRequestHeaders(req *http.Request, pipeline PipelineType, fld } return nil } + func (s *sender) recordMetrics(duration time.Duration, count int64, req *http.Request, resp *http.Response, pipeline PipelineType) { statusCode := 0 diff --git a/exporter/syslogexporter/exporter_test.go b/exporter/syslogexporter/exporter_test.go index 1a42396c66a9..3fc4691379a3 100644 --- a/exporter/syslogexporter/exporter_test.go +++ b/exporter/syslogexporter/exporter_test.go @@ -24,8 +24,10 @@ import ( "go.uber.org/zap" ) -var expectedForm = "<165>1 2003-08-24T12:14:15Z 192.0.2.1 myproc 8710 - - It's time to make the do-nuts.\n" -var originalForm = "<165>1 2003-08-24T05:14:15-07:00 192.0.2.1 myproc 8710 - - It's time to make the do-nuts." +var ( + expectedForm = "<165>1 2003-08-24T12:14:15Z 192.0.2.1 myproc 8710 - - It's time to make the do-nuts.\n" + originalForm = "<165>1 2003-08-24T05:14:15-07:00 192.0.2.1 myproc 8710 - - It's time to make the do-nuts." +) type exporterTest struct { srv net.TCPListener @@ -40,9 +42,11 @@ func exampleLog(t *testing.T) plog.LogRecord { assert.NoError(t, err, "failed to start test syslog server") ts := pcommon.NewTimestampFromTime(timeStr) buffer.SetTimestamp(ts) - attrMap := map[string]any{"proc_id": "8710", "message": "It's time to make the do-nuts.", + attrMap := map[string]any{ + "proc_id": "8710", "message": "It's time to make the do-nuts.", "appname": "myproc", "hostname": "192.0.2.1", "priority": int64(165), - "version": int64(1)} + "version": int64(1), + } for k, v := range attrMap { if _, ok := v.(string); ok { buffer.Attributes().PutStr(k, v.(string)) @@ -70,10 +74,12 @@ func createExporterCreateSettings() exporter.Settings { } func TestInitExporter(t *testing.T) { - _, err := initExporter(&Config{Endpoint: "test.com", + _, err := initExporter(&Config{ + Endpoint: "test.com", Network: "tcp", Port: 514, - Protocol: "rfc5424"}, createExporterCreateSettings()) + Protocol: "rfc5424", + }, createExporterCreateSettings()) assert.NoError(t, err) } @@ -192,22 +198,26 @@ func TestTLSConfig(t *testing.T) { tlsSettings configtls.ClientConfig tlsConfig *tls.Config }{ - {name: "TCP with TLS configuration", + { + name: "TCP with TLS configuration", network: "tcp", tlsSettings: configtls.ClientConfig{}, tlsConfig: &tls.Config{}, }, - {name: "TCP insecure", + { + name: "TCP insecure", network: "tcp", tlsSettings: configtls.ClientConfig{Insecure: true}, tlsConfig: nil, }, - {name: "UDP with TLS configuration", + { + name: "UDP with TLS configuration", network: "udp", tlsSettings: configtls.ClientConfig{}, tlsConfig: nil, }, - {name: "UDP insecure", + { + name: "UDP insecure", network: "udp", tlsSettings: configtls.ClientConfig{Insecure: true}, tlsConfig: nil, @@ -217,11 +227,13 @@ func TestTLSConfig(t *testing.T) { for _, testInstance := range tests { t.Run(testInstance.name, func(t *testing.T) { exporter, err := initExporter( - &Config{Endpoint: "test.com", + &Config{ + Endpoint: "test.com", Network: testInstance.network, Port: 514, Protocol: "rfc5424", - TLSSetting: testInstance.tlsSettings}, + TLSSetting: testInstance.tlsSettings, + }, createExporterCreateSettings()) assert.NoError(t, err) diff --git a/exporter/syslogexporter/rfc3164_formatter.go b/exporter/syslogexporter/rfc3164_formatter.go index 4298a2cb8406..17fa24ebb3ac 100644 --- a/exporter/syslogexporter/rfc3164_formatter.go +++ b/exporter/syslogexporter/rfc3164_formatter.go @@ -10,8 +10,7 @@ import ( "go.opentelemetry.io/collector/pdata/plog" ) -type rfc3164Formatter struct { -} +type rfc3164Formatter struct{} func newRFC3164Formatter() *rfc3164Formatter { return &rfc3164Formatter{} diff --git a/exporter/syslogexporter/sender.go b/exporter/syslogexporter/sender.go index eb8286854dbb..60b08bf37027 100644 --- a/exporter/syslogexporter/sender.go +++ b/exporter/syslogexporter/sender.go @@ -15,23 +15,31 @@ import ( "go.uber.org/zap" ) -const defaultPriority = 165 -const versionRFC5424 = 1 +const ( + defaultPriority = 165 + versionRFC5424 = 1 +) -const protocolRFC5424Str = "rfc5424" -const protocolRFC3164Str = "rfc3164" +const ( + protocolRFC5424Str = "rfc5424" + protocolRFC3164Str = "rfc3164" +) -const priority = "priority" -const version = "version" -const hostname = "hostname" -const app = "appname" -const pid = "proc_id" -const msgID = "msg_id" -const structuredData = "structured_data" -const message = "message" +const ( + priority = "priority" + version = "version" + hostname = "hostname" + app = "appname" + pid = "proc_id" + msgID = "msg_id" + structuredData = "structured_data" + message = "message" +) -const emptyValue = "-" -const emptyMessage = "" +const ( + emptyValue = "-" + emptyMessage = "" +) type sender struct { network string @@ -105,6 +113,7 @@ func (s *sender) Write(ctx context.Context, msgStr string) error { return s.write(msgStr) } + func (s *sender) write(msg string) error { // check if logs contains new line character at the end, if not add it if !strings.HasSuffix(msg, "\n") { diff --git a/exporter/tencentcloudlogserviceexporter/logs_exporter.go b/exporter/tencentcloudlogserviceexporter/logs_exporter.go index bd93c095e3bd..98dad552308c 100644 --- a/exporter/tencentcloudlogserviceexporter/logs_exporter.go +++ b/exporter/tencentcloudlogserviceexporter/logs_exporter.go @@ -35,7 +35,8 @@ type logServiceLogsSender struct { func (s *logServiceLogsSender) pushLogsData( _ context.Context, - md plog.Logs) error { + md plog.Logs, +) error { var err error clsLogs := convertLogs(md) if len(clsLogs) > 0 { diff --git a/exporter/tencentcloudlogserviceexporter/logsdata_to_logservice.go b/exporter/tencentcloudlogserviceexporter/logsdata_to_logservice.go index 8603397dc646..4d16b95a9a3d 100644 --- a/exporter/tencentcloudlogserviceexporter/logsdata_to_logservice.go +++ b/exporter/tencentcloudlogserviceexporter/logsdata_to_logservice.go @@ -116,7 +116,8 @@ func instrumentationLibraryToLogContents(scope pcommon.InstrumentationScope) []* func mapLogRecordToLogService(lr plog.LogRecord, resourceContents, - instrumentationLibraryContents []*cls.Log_Content) *cls.Log { + instrumentationLibraryContents []*cls.Log_Content, +) *cls.Log { if lr.Body().Type() == pcommon.ValueTypeEmpty { return nil } diff --git a/exporter/zipkinexporter/zipkin_test.go b/exporter/zipkinexporter/zipkin_test.go index 4810ac95c0dd..f42423aaf6a9 100644 --- a/exporter/zipkinexporter/zipkin_test.go +++ b/exporter/zipkinexporter/zipkin_test.go @@ -150,6 +150,7 @@ var _ zipkinreporter.Reporter = (*mockZipkinReporter)(nil) func (r *mockZipkinReporter) Send(span zipkinmodel.SpanModel) { r.batch = append(r.batch, &span) } + func (r *mockZipkinReporter) Close() error { return nil }