feat: add max cmd bytes for otel hook

Signed-off-by: rfyiamcool <rfyiamcool@163.com>
This commit is contained in:
rfyiamcool 2024-02-29 12:36:04 +08:00
parent d43a9fa887
commit 47aafdf175
No known key found for this signature in database
GPG Key ID: EBA61C4D83B4DC5C
3 changed files with 50 additions and 4 deletions

View File

@ -19,7 +19,8 @@ type config struct {
tp trace.TracerProvider
tracer trace.Tracer
dbStmtEnabled bool
dbStmtEnabled bool
maxCommandBytes int
// Metrics options.
@ -54,9 +55,10 @@ func newConfig(opts ...baseOption) *config {
dbSystem: "redis",
attrs: []attribute.KeyValue{},
tp: otel.GetTracerProvider(),
mp: otel.GetMeterProvider(),
dbStmtEnabled: true,
tp: otel.GetTracerProvider(),
mp: otel.GetMeterProvider(),
dbStmtEnabled: true,
maxCommandBytes: 0,
}
for _, opt := range opts {
@ -113,6 +115,13 @@ func WithDBStatement(on bool) TracingOption {
})
}
// WithMaxCommandBytes limit the bytes of raw redis commands.
func WithMaxCommandBytes(size int) TracingOption {
return tracingOption(func(conf *config) {
conf.maxCommandBytes = size
})
}
//------------------------------------------------------------------------------
type MetricsOption interface {

View File

@ -2,6 +2,7 @@ package redisotel
import (
"context"
"strings"
"testing"
semconv "go.opentelemetry.io/otel/semconv/v1.7.0"
@ -59,3 +60,21 @@ func TestWithDBStatement(t *testing.T) {
t.Fatal(err)
}
}
func TestMaxString(t *testing.T) {
src := strings.Repeat("a", 100)
dst := maxString(src, 50)
if dst != src[:50] {
t.Fatal("failed to maxstring")
}
dst = maxString(src, 200)
if dst != src {
t.Fatal("failed to maxstring")
}
dst = maxString(src, 0)
if dst != src {
t.Fatal("failed to maxstring")
}
}

View File

@ -27,6 +27,7 @@ func InstrumentTracing(rdb redis.UniversalClient, opts ...TracingOption) error {
connString := formatDBConnString(opt.Network, opt.Addr)
rdb.AddHook(newTracingHook(connString, opts...))
return nil
case *redis.ClusterClient:
rdb.AddHook(newTracingHook("", opts...))
@ -120,6 +121,9 @@ func (th *tracingHook) ProcessHook(hook redis.ProcessHook) redis.ProcessHook {
if th.conf.dbStmtEnabled {
cmdString := rediscmd.CmdString(cmd)
if th.conf.maxCommandBytes > 0 {
cmdString = maxString(cmdString, th.conf.maxCommandBytes)
}
attrs = append(attrs, semconv.DBStatementKey.String(cmdString))
}
@ -157,6 +161,9 @@ func (th *tracingHook) ProcessPipelineHook(
summary, cmdsString := rediscmd.CmdsString(cmds)
if th.conf.dbStmtEnabled {
if th.conf.maxCommandBytes > 0 {
cmdsString = maxString(cmdsString, th.conf.maxCommandBytes)
}
attrs = append(attrs, semconv.DBStatementKey.String(cmdsString))
}
@ -213,3 +220,14 @@ func funcFileLine(pkg string) (string, string, int) {
return fn, file, line
}
func maxString(s string, length int) string {
if length <= 0 { // no define or no limit
return s
}
if len(s) > length {
return s[:length]
}
return s
}