sanitize.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. package tencentcloudlogserviceexporter // import "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/tencentcloudlogserviceexporter"
  4. import (
  5. "strings"
  6. "unicode"
  7. )
  8. // The code for sanitize is mostly copied from:
  9. // https://github.com/open-telemetry/opentelemetry-collector/blob/2e84285efc665798d76773b9901727e8836e9d8f/exporter/prometheusexporter/sanitize.go
  10. // sanitize replaces non-alphanumeric characters with underscores in s.
  11. func sanitize(s string) string {
  12. if len(s) == 0 {
  13. return s
  14. }
  15. // Note: No length limit for label keys because Prometheus doesn't
  16. // define a length limit, thus we should NOT be truncating label keys.
  17. // See https://github.com/orijtech/prometheus-go-metrics-exporter/issues/4.
  18. s = strings.Map(sanitizeRune, s)
  19. if unicode.IsDigit(rune(s[0])) {
  20. s = "key_" + s
  21. }
  22. if s[0] == '_' {
  23. s = "key" + s
  24. }
  25. return s
  26. }
  27. // converts anything that is not a letter or digit to an underscore
  28. func sanitizeRune(r rune) rune {
  29. if unicode.IsLetter(r) || unicode.IsDigit(r) {
  30. return r
  31. }
  32. // Everything else turns into an underscore
  33. return '_'
  34. }