traefik/pkg/tracing/operation_name.go

66 lines
1.8 KiB
Go
Raw Normal View History

2018-11-14 09:18:03 +00:00
package tracing
import (
"crypto/sha256"
"fmt"
"strings"
2022-11-21 17:36:05 +00:00
"github.com/rs/zerolog/log"
2018-11-14 09:18:03 +00:00
)
// TraceNameHashLength defines the number of characters to use from the head of the generated hash.
const TraceNameHashLength = 8
// OperationNameMaxLengthNumber defines the number of static characters in a Span Trace name:
// 8 chars for hash + 2 chars for '_'.
const OperationNameMaxLengthNumber = 10
func generateOperationName(prefix string, parts []string, sep string, spanLimit int) string {
name := prefix + " " + strings.Join(parts, sep)
maxLength := OperationNameMaxLengthNumber + len(prefix) + 1
if spanLimit > 0 && len(name) > spanLimit {
if spanLimit < maxLength {
2022-11-21 17:36:05 +00:00
log.Warn().Msgf("SpanNameLimit cannot be lesser than %d: falling back on %d", maxLength, maxLength+3)
2018-11-14 09:18:03 +00:00
spanLimit = maxLength + 3
}
limit := (spanLimit - maxLength) / 2
var fragments []string
for _, value := range parts {
fragments = append(fragments, truncateString(value, limit))
}
fragments = append(fragments, computeHash(name))
name = prefix + " " + strings.Join(fragments, sep)
}
return name
}
// truncateString reduces the length of the 'str' argument to 'num' - 3 and adds a '...' suffix to the tail.
func truncateString(str string, num int) string {
text := str
if len(str) > num {
if num > 3 {
num -= 3
}
text = str[0:num] + "..."
}
return text
}
// computeHash returns the first TraceNameHashLength character of the sha256 hash for 'name' argument.
func computeHash(name string) string {
data := []byte(name)
hash := sha256.New()
if _, err := hash.Write(data); err != nil {
// Impossible case
2022-11-21 17:36:05 +00:00
log.Error().Str("OperationName", name).Err(err).Msgf("Failed to create Span name hash for %s", name)
2018-11-14 09:18:03 +00:00
}
return fmt.Sprintf("%x", hash.Sum(nil))[:TraceNameHashLength]
}