refactor: replace strings.Replace with strings.ReplaceAll (#11079)

This commit is contained in:
Eng Zer Jun 2022-05-11 23:53:34 +08:00 committed by GitHub
parent fed88fcb44
commit 81090be35d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
38 changed files with 80 additions and 80 deletions

View File

@ -201,7 +201,7 @@ func (a *Aerospike) parseNodeInfo(acc telegraf.Accumulator, stats map[string]str
if len(parts) < 2 { if len(parts) < 2 {
continue continue
} }
key := strings.Replace(parts[0], "-", "_", -1) key := strings.ReplaceAll(parts[0], "-", "_")
nFields[key] = parseAerospikeValue(key, parts[1]) nFields[key] = parseAerospikeValue(key, parts[1])
} }
acc.AddFields("aerospike_node", nFields, nTags, time.Now()) acc.AddFields("aerospike_node", nFields, nTags, time.Now())
@ -244,7 +244,7 @@ func (a *Aerospike) parseNamespaceInfo(acc telegraf.Accumulator, stats map[strin
if len(parts) < 2 { if len(parts) < 2 {
continue continue
} }
key := strings.Replace(parts[0], "-", "_", -1) key := strings.ReplaceAll(parts[0], "-", "_")
nFields[key] = parseAerospikeValue(key, parts[1]) nFields[key] = parseAerospikeValue(key, parts[1])
} }
acc.AddFields("aerospike_namespace", nFields, nTags, time.Now()) acc.AddFields("aerospike_namespace", nFields, nTags, time.Now())
@ -311,7 +311,7 @@ func (a *Aerospike) parseSetInfo(acc telegraf.Accumulator, stats map[string]stri
continue continue
} }
key := strings.Replace(pieces[0], "-", "_", -1) key := strings.ReplaceAll(pieces[0], "-", "_")
nFields[key] = parseAerospikeValue(key, pieces[1]) nFields[key] = parseAerospikeValue(key, pieces[1])
} }
acc.AddFields("aerospike_set", nFields, nTags, time.Now()) acc.AddFields("aerospike_set", nFields, nTags, time.Now())
@ -403,7 +403,7 @@ func (a *Aerospike) parseHistogram(acc telegraf.Accumulator, stats map[string]st
} }
} }
acc.AddFields(fmt.Sprintf("aerospike_histogram_%v", strings.Replace(histogramType, "-", "_", -1)), nFields, nTags, time.Now()) acc.AddFields(fmt.Sprintf("aerospike_histogram_%v", strings.ReplaceAll(histogramType, "-", "_")), nFields, nTags, time.Now())
} }
func splitNamespaceSet(namespaceSet string) (namespace string, set string) { func splitNamespaceSet(namespaceSet string) (namespace string, set string) {

View File

@ -473,14 +473,14 @@ func formatField(metricName string, statistic string) string {
} }
func formatMeasurement(project string) string { func formatMeasurement(project string) string {
project = strings.Replace(project, "/", "_", -1) project = strings.ReplaceAll(project, "/", "_")
project = snakeCase(project) project = snakeCase(project)
return fmt.Sprintf("aliyuncms_%s", project) return fmt.Sprintf("aliyuncms_%s", project)
} }
func snakeCase(s string) string { func snakeCase(s string) string {
s = internal.SnakeCase(s) s = internal.SnakeCase(s)
s = strings.Replace(s, "__", "_", -1) s = strings.ReplaceAll(s, "__", "_")
return s return s
} }

View File

@ -141,7 +141,7 @@ func genTagsFields(gpus map[string]GPU, system map[string]sysInfo) []metric {
setTagIfUsed(tags, "gpu_id", payload.GpuID) setTagIfUsed(tags, "gpu_id", payload.GpuID)
setTagIfUsed(tags, "gpu_unique_id", payload.GpuUniqueID) setTagIfUsed(tags, "gpu_unique_id", payload.GpuUniqueID)
setIfUsed("int", fields, "driver_version", strings.Replace(system["system"].DriverVersion, ".", "", -1)) setIfUsed("int", fields, "driver_version", strings.ReplaceAll(system["system"].DriverVersion, ".", ""))
setIfUsed("int", fields, "fan_speed", payload.GpuFanSpeedPercentage) setIfUsed("int", fields, "fan_speed", payload.GpuFanSpeedPercentage)
setIfUsed("int64", fields, "memory_total", payload.GpuVRAMTotalMemory) setIfUsed("int64", fields, "memory_total", payload.GpuVRAMTotalMemory)
setIfUsed("int64", fields, "memory_used", payload.GpuVRAMTotalUsedMemory) setIfUsed("int64", fields, "memory_used", payload.GpuVRAMTotalUsedMemory)

View File

@ -107,7 +107,7 @@ func (n *Apache) gatherURL(addr *url.URL, acc telegraf.Accumulator) error {
line := sc.Text() line := sc.Text()
if strings.Contains(line, ":") { if strings.Contains(line, ":") {
parts := strings.SplitN(line, ":", 2) parts := strings.SplitN(line, ":", 2)
key, part := strings.Replace(parts[0], " ", "", -1), strings.TrimSpace(parts[1]) key, part := strings.ReplaceAll(parts[0], " ", ""), strings.TrimSpace(parts[1])
switch key { switch key {
case "Scoreboard": case "Scoreboard":

View File

@ -16,7 +16,7 @@ import (
// remap uri to json file, eg: /v3/kafka -> ./testdata/v3_kafka.json // remap uri to json file, eg: /v3/kafka -> ./testdata/v3_kafka.json
func getResponseJSON(requestURI string) ([]byte, int) { func getResponseJSON(requestURI string) ([]byte, int) {
uri := strings.TrimLeft(requestURI, "/") uri := strings.TrimLeft(requestURI, "/")
mappedFile := strings.Replace(uri, "/", "_", -1) mappedFile := strings.ReplaceAll(uri, "/", "_")
jsonFile := fmt.Sprintf("./testdata/%s.json", mappedFile) jsonFile := fmt.Sprintf("./testdata/%s.json", mappedFile)
code := 200 code := 200

View File

@ -299,8 +299,8 @@ func (c *Ceph) execute(command string) (string, error) {
// Ceph doesn't sanitize its output, and may return invalid JSON. Patch this // Ceph doesn't sanitize its output, and may return invalid JSON. Patch this
// up for them, as having some inaccurate data is better than none. // up for them, as having some inaccurate data is better than none.
output = strings.Replace(output, "-inf", "0", -1) output = strings.ReplaceAll(output, "-inf", "0")
output = strings.Replace(output, "inf", "0", -1) output = strings.ReplaceAll(output, "inf", "0")
return output, nil return output, nil
} }

View File

@ -82,7 +82,7 @@ func processChronycOutput(out string) (map[string]interface{}, map[string]string
if len(stats) < 2 { if len(stats) < 2 {
return nil, nil, fmt.Errorf("unexpected output from chronyc, expected ':' in %s", out) return nil, nil, fmt.Errorf("unexpected output from chronyc, expected ':' in %s", out)
} }
name := strings.ToLower(strings.Replace(strings.TrimSpace(stats[0]), " ", "_", -1)) name := strings.ToLower(strings.ReplaceAll(strings.TrimSpace(stats[0]), " ", "_"))
// ignore reference time // ignore reference time
if strings.Contains(name, "ref_time") { if strings.Contains(name, "ref_time") {
continue continue

View File

@ -136,7 +136,7 @@ func (c *CiscoTelemetryMDT) Start(acc telegraf.Accumulator) error {
// Fill extra tags // Fill extra tags
c.extraTags = make(map[string]map[string]struct{}) c.extraTags = make(map[string]map[string]struct{})
for _, tag := range c.EmbeddedTags { for _, tag := range c.EmbeddedTags {
dir := strings.Replace(path.Dir(tag), "-", "_", -1) dir := strings.ReplaceAll(path.Dir(tag), "-", "_")
if _, hasKey := c.extraTags[dir]; !hasKey { if _, hasKey := c.extraTags[dir]; !hasKey {
c.extraTags[dir] = make(map[string]struct{}) c.extraTags[dir] = make(map[string]struct{})
} }
@ -441,7 +441,7 @@ func decodeTag(field *telemetry.TelemetryField) string {
// Recursively parse tag fields // Recursively parse tag fields
func (c *CiscoTelemetryMDT) parseKeyField(tags map[string]string, field *telemetry.TelemetryField, prefix string) { func (c *CiscoTelemetryMDT) parseKeyField(tags map[string]string, field *telemetry.TelemetryField, prefix string) {
localname := strings.Replace(field.Name, "-", "_", -1) localname := strings.ReplaceAll(field.Name, "-", "_")
name := localname name := localname
if len(localname) == 0 { if len(localname) == 0 {
name = prefix name = prefix
@ -529,7 +529,7 @@ func (c *CiscoTelemetryMDT) parseClassAttributeField(grouper *metric.SeriesGroup
func (c *CiscoTelemetryMDT) parseContentField(grouper *metric.SeriesGrouper, field *telemetry.TelemetryField, prefix string, func (c *CiscoTelemetryMDT) parseContentField(grouper *metric.SeriesGrouper, field *telemetry.TelemetryField, prefix string,
encodingPath string, tags map[string]string, timestamp time.Time) { encodingPath string, tags map[string]string, timestamp time.Time) {
name := strings.Replace(field.Name, "-", "_", -1) name := strings.ReplaceAll(field.Name, "-", "_")
if (name == "modTs" || name == "createTs") && decodeValue(field) == "never" { if (name == "modTs" || name == "createTs") && decodeValue(field) == "never" {
return return
@ -540,7 +540,7 @@ func (c *CiscoTelemetryMDT) parseContentField(grouper *metric.SeriesGrouper, fie
name = prefix + "/" + name name = prefix + "/" + name
} }
extraTags := c.extraTags[strings.Replace(encodingPath, "-", "_", -1)+"/"+name] extraTags := c.extraTags[strings.ReplaceAll(encodingPath, "-", "_")+"/"+name]
if value := decodeValue(field); value != nil { if value := decodeValue(field); value != nil {
// Do alias lookup, to shorten measurement names // Do alias lookup, to shorten measurement names
@ -571,7 +571,7 @@ func (c *CiscoTelemetryMDT) parseContentField(grouper *metric.SeriesGrouper, fie
if len(extraTags) > 0 { if len(extraTags) > 0 {
for _, subfield := range field.Fields { for _, subfield := range field.Fields {
if _, isExtraTag := extraTags[subfield.Name]; isExtraTag { if _, isExtraTag := extraTags[subfield.Name]; isExtraTag {
tags[name+"/"+strings.Replace(subfield.Name, "-", "_", -1)] = decodeTag(subfield) tags[name+"/"+strings.ReplaceAll(subfield.Name, "-", "_")] = decodeTag(subfield)
} }
} }
} }

View File

@ -522,15 +522,15 @@ func New() *CloudWatch {
} }
func sanitizeMeasurement(namespace string) string { func sanitizeMeasurement(namespace string) string {
namespace = strings.Replace(namespace, "/", "_", -1) namespace = strings.ReplaceAll(namespace, "/", "_")
namespace = snakeCase(namespace) namespace = snakeCase(namespace)
return "cloudwatch_" + namespace return "cloudwatch_" + namespace
} }
func snakeCase(s string) string { func snakeCase(s string) string {
s = internal.SnakeCase(s) s = internal.SnakeCase(s)
s = strings.Replace(s, " ", "_", -1) s = strings.ReplaceAll(s, " ", "_")
s = strings.Replace(s, "__", "_", -1) s = strings.ReplaceAll(s, "__", "_")
return s return s
} }

View File

@ -175,7 +175,7 @@ type point struct {
func (d *DCOS) createPoints(m *Metrics) []*point { func (d *DCOS) createPoints(m *Metrics) []*point {
points := make(map[string]*point) points := make(map[string]*point)
for _, dp := range m.Datapoints { for _, dp := range m.Datapoints {
fieldKey := strings.Replace(dp.Name, ".", "_", -1) fieldKey := strings.ReplaceAll(dp.Name, ".", "_")
tags := dp.Tags tags := dp.Tags
if tags == nil { if tags == nil {

View File

@ -46,7 +46,7 @@ func (ds *DiskStats) Gather(acc telegraf.Accumulator) error {
mountOpts := MountOptions(partitions[i].Opts) mountOpts := MountOptions(partitions[i].Opts)
tags := map[string]string{ tags := map[string]string{
"path": du.Path, "path": du.Path,
"device": strings.Replace(partitions[i].Device, "/dev/", "", -1), "device": strings.ReplaceAll(partitions[i].Device, "/dev/", ""),
"fstype": du.Fstype, "fstype": du.Fstype,
"mode": mountOpts.Mode(), "mode": mountOpts.Mode(),
} }

View File

@ -328,7 +328,7 @@ func (d *Docker) gatherInfo(acc telegraf.Accumulator) error {
) )
for _, rawData := range info.DriverStatus { for _, rawData := range info.DriverStatus {
name := strings.ToLower(strings.Replace(rawData[0], " ", "_", -1)) name := strings.ToLower(strings.ReplaceAll(rawData[0], " ", "_"))
if name == "pool_name" { if name == "pool_name" {
poolName = rawData[1] poolName = rawData[1]
continue continue

View File

@ -153,7 +153,7 @@ func (aggregation *esAggregation) buildAggregationQuery() error {
measurement: aggregation.MeasurementName, measurement: aggregation.MeasurementName,
function: aggregation.MetricFunction, function: aggregation.MetricFunction,
field: k, field: k,
name: strings.Replace(k, ".", "_", -1) + "_" + aggregation.MetricFunction, name: strings.ReplaceAll(k, ".", "_") + "_" + aggregation.MetricFunction,
}, },
isParent: true, isParent: true,
aggregation: agg, aggregation: agg,
@ -185,7 +185,7 @@ func (aggregation *esAggregation) buildAggregationQuery() error {
measurement: aggregation.MeasurementName, measurement: aggregation.MeasurementName,
function: "terms", function: "terms",
field: term, field: term,
name: strings.Replace(term, ".", "_", -1), name: strings.ReplaceAll(term, ".", "_"),
}, },
isParent: true, isParent: true,
aggregation: agg, aggregation: agg,

View File

@ -546,9 +546,9 @@ func setupIntegrationTest() error {
logline := nginxlog{ logline := nginxlog{
IPaddress: parts[0], IPaddress: parts[0],
Timestamp: time.Now().UTC(), Timestamp: time.Now().UTC(),
Method: strings.Replace(parts[5], `"`, "", -1), Method: strings.ReplaceAll(parts[5], `"`, ""),
URI: parts[6], URI: parts[6],
Httpversion: strings.Replace(parts[7], `"`, "", -1), Httpversion: strings.ReplaceAll(parts[7], `"`, ""),
Response: parts[8], Response: parts[8],
Size: float64(size), Size: float64(size),
ResponseTime: float64(responseTime), ResponseTime: float64(responseTime),

View File

@ -413,7 +413,7 @@ func (c *GNMI) handleTelemetryField(update *gnmiLib.Update, tags map[string]stri
jsondata = val.JsonVal jsondata = val.JsonVal
} }
name := strings.Replace(gpath, "-", "_", -1) name := strings.ReplaceAll(gpath, "-", "_")
fields := make(map[string]interface{}) fields := make(map[string]interface{})
if value != nil { if value != nil {
fields[name] = value fields[name] = value
@ -462,7 +462,7 @@ func (c *GNMI) handlePath(gnmiPath *gnmiLib.Path, tags map[string]string, prefix
if tags != nil { if tags != nil {
for key, val := range elem.Key { for key, val := range elem.Key {
key = strings.Replace(key, "-", "_", -1) key = strings.ReplaceAll(key, "-", "_")
// Use short-form of key if possible // Use short-form of key if possible
if _, exists := tags[key]; exists { if _, exists := tags[key]; exists {

View File

@ -233,7 +233,7 @@ func (r *IntelRDT) readData(ctx context.Context, args []string, processesPIDsAss
if r.UseSudo { if r.UseSudo {
// run pqos with `/bin/sh -c "sudo /path/to/pqos ..."` // run pqos with `/bin/sh -c "sudo /path/to/pqos ..."`
args = []string{"-c", fmt.Sprintf("sudo %s %s", r.PqosPath, strings.Replace(strings.Join(args, " "), ";", "\\;", -1))} args = []string{"-c", fmt.Sprintf("sudo %s %s", r.PqosPath, strings.ReplaceAll(strings.Join(args, " "), ";", "\\;"))}
cmd = exec.Command("/bin/sh", args...) cmd = exec.Command("/bin/sh", args...)
} }

View File

@ -278,7 +278,7 @@ func trim(s string) string {
func transform(s string) string { func transform(s string) string {
s = trim(s) s = trim(s)
s = strings.ToLower(s) s = strings.ToLower(s)
return strings.Replace(s, " ", "_", -1) return strings.ReplaceAll(s, " ", "_")
} }
func init() { func init() {

View File

@ -143,7 +143,7 @@ func (pb *pointBuilder) formatFieldName(attribute, path string) string {
} }
if path != "" { if path != "" {
fieldName = fieldName + fieldSeparator + strings.Replace(path, "/", fieldSeparator, -1) fieldName = fieldName + fieldSeparator + strings.ReplaceAll(path, "/", fieldSeparator)
} }
return fieldName return fieldName
@ -200,7 +200,7 @@ func (pb *pointBuilder) applySubstitutions(mbean string, fieldMap map[string]int
substitution := properties[subKey] substitution := properties[subKey]
for fieldName, fieldValue := range fieldMap { for fieldName, fieldValue := range fieldMap {
newFieldName := strings.Replace(fieldName, symbol, substitution, -1) newFieldName := strings.ReplaceAll(fieldName, symbol, substitution)
if fieldName != newFieldName { if fieldName != newFieldName {
fieldMap[newFieldName] = fieldValue fieldMap[newFieldName] = fieldValue
delete(fieldMap, fieldName) delete(fieldMap, fieldName)

View File

@ -74,7 +74,7 @@ func spitTagsNPath(xmlpath string) (string, map[string]string) {
// we must emit multiple tags // we must emit multiple tags
for _, kv := range strings.Split(sub[2], " and ") { for _, kv := range strings.Split(sub[2], " and ") {
key := tagKey + strings.TrimSpace(strings.Split(kv, "=")[0]) key := tagKey + strings.TrimSpace(strings.Split(kv, "=")[0])
tagValue := strings.Replace(strings.Split(kv, "=")[1], "'", "", -1) tagValue := strings.ReplaceAll(strings.Split(kv, "=")[1], "'", "")
tags[key] = tagValue tags[key] = tagValue
} }

View File

@ -1875,8 +1875,8 @@ func (m *Mysql) parseValueByDatabaseTypeName(value sql.RawBytes, databaseTypeNam
func findThreadState(rawCommand, rawState string) string { func findThreadState(rawCommand, rawState string) string {
var ( var (
// replace '_' symbol with space // replace '_' symbol with space
command = strings.Replace(strings.ToLower(rawCommand), "_", " ", -1) command = strings.ReplaceAll(strings.ToLower(rawCommand), "_", " ")
state = strings.Replace(strings.ToLower(rawState), "_", " ", -1) state = strings.ReplaceAll(strings.ToLower(rawState), "_", " ")
) )
// if the state is already valid, then return it // if the state is already valid, then return it
if _, ok := generalThreadStates[state]; ok { if _, ok := generalThreadStates[state]; ok {
@ -1909,7 +1909,7 @@ func findThreadState(rawCommand, rawState string) string {
// newNamespace can be used to make a namespace // newNamespace can be used to make a namespace
func newNamespace(words ...string) string { func newNamespace(words ...string) string {
return strings.Replace(strings.Join(words, "_"), " ", "_", -1) return strings.ReplaceAll(strings.Join(words, "_"), " ", "_")
} }
func copyTags(in map[string]string) map[string]string { func copyTags(in map[string]string) map[string]string {

View File

@ -110,7 +110,7 @@ func (s *NSD) Gather(acc telegraf.Accumulator) error {
} }
} }
} else { } else {
field := strings.Replace(stat, ".", "_", -1) field := strings.ReplaceAll(stat, ".", "_")
fields[field] = fieldValue fields[field] = fieldValue
} }
} }

View File

@ -170,8 +170,8 @@ func dnToMetric(dn string, o *Openldap) string {
var metricParts []string var metricParts []string
dn = strings.Trim(dn, " ") dn = strings.Trim(dn, " ")
dn = strings.Replace(dn, " ", "_", -1) dn = strings.ReplaceAll(dn, " ", "_")
dn = strings.Replace(dn, "cn=", "", -1) dn = strings.ReplaceAll(dn, "cn=", "")
dn = strings.ToLower(dn) dn = strings.ToLower(dn)
metricParts = strings.Split(dn, ",") metricParts = strings.Split(dn, ",")
for i, j := 0, len(metricParts)-1; i < j; i, j = i+1, j-1 { for i, j := 0, len(metricParts)-1; i < j; i, j = i+1, j-1 {
@ -181,12 +181,12 @@ func dnToMetric(dn string, o *Openldap) string {
} }
metricName := strings.Trim(dn, " ") metricName := strings.Trim(dn, " ")
metricName = strings.Replace(metricName, " ", "_", -1) metricName = strings.ReplaceAll(metricName, " ", "_")
metricName = strings.ToLower(metricName) metricName = strings.ToLower(metricName)
metricName = strings.TrimPrefix(metricName, "cn=") metricName = strings.TrimPrefix(metricName, "cn=")
metricName = strings.Replace(metricName, strings.ToLower("cn=Monitor"), "", -1) metricName = strings.ReplaceAll(metricName, strings.ToLower("cn=Monitor"), "")
metricName = strings.Replace(metricName, "cn=", "_", -1) metricName = strings.ReplaceAll(metricName, "cn=", "_")
return strings.Replace(metricName, ",", "", -1) return strings.ReplaceAll(metricName, ",", "")
} }
func init() { func init() {

View File

@ -87,7 +87,7 @@ func (s *Opensmtpd) Gather(acc telegraf.Accumulator) error {
continue continue
} }
field := strings.Replace(stat, ".", "_", -1) field := strings.ReplaceAll(stat, ".", "_")
fields[field], err = strconv.ParseFloat(value, 64) fields[field], err = strconv.ParseFloat(value, 64)
if err != nil { if err != nil {

View File

@ -227,7 +227,7 @@ func importMetric(r io.Reader, acc telegraf.Accumulator, addr string) {
} }
fields := make(map[string]interface{}) fields := make(map[string]interface{})
for k, v := range stats[pool] { for k, v := range stats[pool] {
fields[strings.Replace(k, " ", "_", -1)] = v fields[strings.ReplaceAll(k, " ", "_")] = v
} }
acc.AddFields("phpfpm", fields, tags) acc.AddFields("phpfpm", fields, tags)
} }

View File

@ -138,7 +138,7 @@ func prepareFieldValues(fields map[string]string, typeMap map[string]configField
preparedFields := make(map[string]interface{}) preparedFields := make(map[string]interface{})
for key, val := range fields { for key, val := range fields {
key = strings.Replace(key, "-", "_", -1) key = strings.ReplaceAll(key, "-", "_")
valType, ok := typeMap[key] valType, ok := typeMap[key]
if !ok { if !ok {

View File

@ -92,7 +92,7 @@ func (s *Sensors) parse(acc telegraf.Accumulator) error {
// snake converts string to snake case // snake converts string to snake case
func snake(input string) string { func snake(input string) string {
return strings.ToLower(strings.Replace(strings.TrimSpace(input), " ", "_", -1)) return strings.ToLower(strings.ReplaceAll(strings.TrimSpace(input), " ", "_"))
} }
func init() { func init() {

View File

@ -730,12 +730,12 @@ func (m *Smart) gatherDisk(acc telegraf.Accumulator, device string, wg *sync.Wai
wwn := wwnInfo.FindStringSubmatch(line) wwn := wwnInfo.FindStringSubmatch(line)
if len(wwn) > 1 { if len(wwn) > 1 {
deviceTags["wwn"] = strings.Replace(wwn[1], " ", "", -1) deviceTags["wwn"] = strings.ReplaceAll(wwn[1], " ", "")
} }
capacity := userCapacityInfo.FindStringSubmatch(line) capacity := userCapacityInfo.FindStringSubmatch(line)
if len(capacity) > 1 { if len(capacity) > 1 {
deviceTags["capacity"] = strings.Replace(capacity[1], ",", "", -1) deviceTags["capacity"] = strings.ReplaceAll(capacity[1], ",", "")
} }
enabled := smartEnabledInfo.FindStringSubmatch(line) enabled := smartEnabledInfo.FindStringSubmatch(line)
@ -1004,7 +1004,7 @@ func parseDataUnits(fields, deviceFields map[string]interface{}, str string) err
} }
func parseCommaSeparatedIntWithAccumulator(acc telegraf.Accumulator, fields map[string]interface{}, tags map[string]string, str string) error { func parseCommaSeparatedIntWithAccumulator(acc telegraf.Accumulator, fields map[string]interface{}, tags map[string]string, str string) error {
i, err := strconv.ParseInt(strings.Replace(str, ",", "", -1), 10, 64) i, err := strconv.ParseInt(strings.ReplaceAll(str, ",", ""), 10, 64)
if err != nil { if err != nil {
return err return err
} }

View File

@ -713,8 +713,8 @@ func (s *Statsd) parseName(bucket string) (name string, field string, tags map[s
} }
if s.ConvertNames { if s.ConvertNames {
name = strings.Replace(name, ".", "_", -1) name = strings.ReplaceAll(name, ".", "_")
name = strings.Replace(name, "-", "__", -1) name = strings.ReplaceAll(name, "-", "__")
} }
if field == "" { if field == "" {
field = defaultFieldName field = defaultFieldName

View File

@ -151,7 +151,7 @@ func (s *Unbound) Gather(acc telegraf.Accumulator) error {
} }
} }
} else { } else {
field := strings.Replace(stat, ".", "_", -1) field := strings.ReplaceAll(stat, ".", "_")
fields[field] = fieldValue fields[field] = fieldValue
} }
} }

View File

@ -55,11 +55,11 @@ func (a *Amon) Write(metrics []telegraf.Metric) error {
metricCounter := 0 metricCounter := 0
for _, m := range metrics { for _, m := range metrics {
mname := strings.Replace(m.Name(), "_", ".", -1) mname := strings.ReplaceAll(m.Name(), "_", ".")
if amonPts, err := buildMetrics(m); err == nil { if amonPts, err := buildMetrics(m); err == nil {
for fieldName, amonPt := range amonPts { for fieldName, amonPt := range amonPts {
metric := &Metric{ metric := &Metric{
Metric: mname + "_" + strings.Replace(fieldName, "_", ".", -1), Metric: mname + "_" + strings.ReplaceAll(fieldName, "_", "."),
} }
metric.Points[0] = amonPt metric.Points[0] = amonPt
tempSeries = append(tempSeries, metric) tempSeries = append(tempSeries, metric)

View File

@ -183,7 +183,7 @@ func escapeObject(m map[string]interface{}, keyReplacement string) (string, erro
// escapeString wraps s in the given quote string and replaces all occurrences // escapeString wraps s in the given quote string and replaces all occurrences
// of it inside of s with a double quote. // of it inside of s with a double quote.
func escapeString(s string, quote string) string { func escapeString(s string, quote string) string {
return quote + strings.Replace(s, quote, quote+quote, -1) + quote return quote + strings.ReplaceAll(s, quote, quote+quote) + quote
} }
// hashID returns a cryptographic hash int64 hash that includes the metric name // hashID returns a cryptographic hash int64 hash that includes the metric name

View File

@ -148,13 +148,13 @@ func (d *Datadog) Write(metrics []telegraf.Metric) error {
} }
if err != nil { if err != nil {
return fmt.Errorf("unable to create http.Request, %s", strings.Replace(err.Error(), d.Apikey, redactedAPIKey, -1)) return fmt.Errorf("unable to create http.Request, %s", strings.ReplaceAll(err.Error(), d.Apikey, redactedAPIKey))
} }
req.Header.Add("Content-Type", "application/json") req.Header.Add("Content-Type", "application/json")
resp, err := d.client.Do(req) resp, err := d.client.Do(req)
if err != nil { if err != nil {
return fmt.Errorf("error POSTing metrics, %s", strings.Replace(err.Error(), d.Apikey, redactedAPIKey, -1)) return fmt.Errorf("error POSTing metrics, %s", strings.ReplaceAll(err.Error(), d.Apikey, redactedAPIKey))
} }
defer resp.Body.Close() defer resp.Body.Close()

View File

@ -71,12 +71,12 @@ func (p *SQL) Close() error {
// Quote an identifier (table or column name) // Quote an identifier (table or column name)
func quoteIdent(name string) string { func quoteIdent(name string) string {
return `"` + strings.Replace(sanitizeQuoted(name), `"`, `""`, -1) + `"` return `"` + strings.ReplaceAll(sanitizeQuoted(name), `"`, `""`) + `"`
} }
// Quote a string literal // Quote a string literal
func quoteStr(name string) string { func quoteStr(name string) string {
return "'" + strings.Replace(name, "'", "''", -1) + "'" return "'" + strings.ReplaceAll(name, "'", "''") + "'"
} }
func sanitizeQuoted(in string) string { func sanitizeQuoted(in string) string {
@ -143,10 +143,10 @@ func (p *SQL) generateCreateTable(metric telegraf.Metric) string {
} }
query := p.TableTemplate query := p.TableTemplate
query = strings.Replace(query, "{TABLE}", quoteIdent(metric.Name()), -1) query = strings.ReplaceAll(query, "{TABLE}", quoteIdent(metric.Name()))
query = strings.Replace(query, "{TABLELITERAL}", quoteStr(metric.Name()), -1) query = strings.ReplaceAll(query, "{TABLELITERAL}", quoteStr(metric.Name()))
query = strings.Replace(query, "{COLUMNS}", strings.Join(columns, ","), -1) query = strings.ReplaceAll(query, "{COLUMNS}", strings.Join(columns, ","))
//query = strings.Replace(query, "{KEY_COLUMNS}", strings.Join(pk, ","), -1) //query = strings.ReplaceAll(query, "{KEY_COLUMNS}", strings.Join(pk, ","))
return query return query
} }
@ -175,7 +175,7 @@ func (p *SQL) generateInsert(tablename string, columns []string) string {
} }
func (p *SQL) tableExists(tableName string) bool { func (p *SQL) tableExists(tableName string) bool {
stmt := strings.Replace(p.TableExistsTemplate, "{TABLE}", quoteIdent(tableName), -1) stmt := strings.ReplaceAll(p.TableExistsTemplate, "{TABLE}", quoteIdent(tableName))
_, err := p.db.Exec(stmt) _, err := p.db.Exec(stmt)
return err == nil return err == nil

View File

@ -162,7 +162,7 @@ func buildValue(v interface{}) (string, error) {
case int64: case int64:
retv = intToString(p) retv = intToString(p)
case string: case string:
retv = fmt.Sprintf("'%s'", strings.Replace(p, "'", "\\'", -1)) retv = fmt.Sprintf("'%s'", strings.ReplaceAll(p, "'", "\\'"))
case bool: case bool:
retv = boolToString(p) retv = boolToString(p)
case uint64: case uint64:

View File

@ -291,7 +291,7 @@ func (p *Parser) ParseLine(line string) (telegraf.Metric, error) {
if len(parts) == 2 { if len(parts) == 2 {
padded := fmt.Sprintf("%-9s", parts[1]) padded := fmt.Sprintf("%-9s", parts[1])
nsString := strings.Replace(padded[:9], " ", "0", -1) nsString := strings.ReplaceAll(padded[:9], " ", "0")
nanosec, err := strconv.ParseInt(nsString, 10, 64) nanosec, err := strconv.ParseInt(nsString, 10, 64)
if err != nil { if err != nil {
p.Log.Errorf("Error parsing %s to timestamp: %s", v, err) p.Log.Errorf("Error parsing %s to timestamp: %s", v, err)
@ -357,7 +357,7 @@ func (p *Parser) ParseLine(line string) (telegraf.Metric, error) {
case Drop: case Drop:
// goodbye! // goodbye!
default: default:
v = strings.Replace(v, ",", ".", -1) v = strings.ReplaceAll(v, ",", ".")
ts, err := time.ParseInLocation(t, v, p.loc) ts, err := time.ParseInLocation(t, v, p.loc)
if err == nil { if err == nil {
if ts.Year() == 0 { if ts.Year() == 0 {

View File

@ -224,7 +224,7 @@ func (s *Strings) initOnce() {
for _, c := range s.Replace { for _, c := range s.Replace {
c := c c := c
c.fn = func(s string) string { c.fn = func(s string) string {
newString := strings.Replace(s, c.Old, c.New, -1) newString := strings.ReplaceAll(s, c.Old, c.New)
if newString == "" { if newString == "" {
return s return s
} }

View File

@ -90,14 +90,14 @@ func (s *Serializer) createObject(metric telegraf.Metric) []byte {
} }
for _, tag := range metric.TagList() { for _, tag := range metric.TagList() {
m.WriteString(strings.Replace(tag.Key, " ", "_", -1)) //nolint:revive // from buffer.go: "err is always nil" m.WriteString(strings.ReplaceAll(tag.Key, " ", "_")) //nolint:revive // from buffer.go: "err is always nil"
m.WriteString("=") //nolint:revive // from buffer.go: "err is always nil" m.WriteString("=") //nolint:revive // from buffer.go: "err is always nil"
value := tag.Value value := tag.Value
if len(value) == 0 { if len(value) == 0 {
value = "null" value = "null"
} }
m.WriteString(strings.Replace(value, " ", "_", -1)) //nolint:revive // from buffer.go: "err is always nil" m.WriteString(strings.ReplaceAll(value, " ", "_")) //nolint:revive // from buffer.go: "err is always nil"
m.WriteString(" ") //nolint:revive // from buffer.go: "err is always nil" m.WriteString(" ") //nolint:revive // from buffer.go: "err is always nil"
} }
m.WriteString(" ") //nolint:revive // from buffer.go: "err is always nil" m.WriteString(" ") //nolint:revive // from buffer.go: "err is always nil"
m.WriteString(formatValue(fieldValue)) //nolint:revive // from buffer.go: "err is always nil" m.WriteString(formatValue(fieldValue)) //nolint:revive // from buffer.go: "err is always nil"
@ -122,15 +122,15 @@ func (s *Serializer) IsMetricsFormatUnset() bool {
func serializeMetricFieldSeparate(name, fieldName string) string { func serializeMetricFieldSeparate(name, fieldName string) string {
return fmt.Sprintf("metric=%s field=%s ", return fmt.Sprintf("metric=%s field=%s ",
strings.Replace(name, " ", "_", -1), strings.ReplaceAll(name, " ", "_"),
strings.Replace(fieldName, " ", "_", -1), strings.ReplaceAll(fieldName, " ", "_"),
) )
} }
func serializeMetricIncludeField(name, fieldName string) string { func serializeMetricIncludeField(name, fieldName string) string {
return fmt.Sprintf("metric=%s_%s ", return fmt.Sprintf("metric=%s_%s ",
strings.Replace(name, " ", "_", -1), strings.ReplaceAll(name, " ", "_"),
strings.Replace(fieldName, " ", "_", -1), strings.ReplaceAll(fieldName, " ", "_"),
) )
} }

View File

@ -180,7 +180,7 @@ func SerializeBucketName(
default: default:
// This is a tag being applied // This is a tag being applied
if tagvalue, ok := tagsCopy[templatePart]; ok { if tagvalue, ok := tagsCopy[templatePart]; ok {
out = append(out, strings.Replace(tagvalue, ".", "_", -1)) out = append(out, strings.ReplaceAll(tagvalue, ".", "_"))
delete(tagsCopy, templatePart) delete(tagsCopy, templatePart)
} }
} }
@ -307,7 +307,7 @@ func buildTags(tags map[string]string) string {
var tagStr string var tagStr string
for i, k := range keys { for i, k := range keys {
tagValue := strings.Replace(tags[k], ".", "_", -1) tagValue := strings.ReplaceAll(tags[k], ".", "_")
if i == 0 { if i == 0 {
tagStr += tagValue tagStr += tagValue
} else { } else {