redis/extra/redisotel/redisotel.go

79 lines
1.8 KiB
Go
Raw Permalink Normal View History

2020-10-21 15:19:27 +03:00
package redisotel
import (
"context"
"github.com/go-redis/redis/extra/rediscmd/v8"
2020-10-21 15:19:27 +03:00
"github.com/go-redis/redis/v8"
2020-11-21 10:56:52 +03:00
"go.opentelemetry.io/otel"
2021-03-04 04:43:10 +03:00
"go.opentelemetry.io/otel/attribute"
2020-11-21 10:56:52 +03:00
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
2020-10-21 15:19:27 +03:00
)
2020-11-21 10:56:52 +03:00
var tracer = otel.Tracer("github.com/go-redis/redis")
2020-10-21 15:19:27 +03:00
type TracingHook struct{}
2021-04-16 15:00:10 +03:00
var _ redis.Hook = (*TracingHook)(nil)
func NewTracingHook() *TracingHook {
return new(TracingHook)
}
2020-10-21 15:19:27 +03:00
func (TracingHook) BeforeProcess(ctx context.Context, cmd redis.Cmder) (context.Context, error) {
if !trace.SpanFromContext(ctx).IsRecording() {
return ctx, nil
}
ctx, span := tracer.Start(ctx, cmd.FullName())
span.SetAttributes(
2021-03-04 04:43:10 +03:00
attribute.String("db.system", "redis"),
attribute.String("db.statement", rediscmd.CmdString(cmd)),
2020-10-21 15:19:27 +03:00
)
return ctx, nil
}
func (TracingHook) AfterProcess(ctx context.Context, cmd redis.Cmder) error {
span := trace.SpanFromContext(ctx)
if err := cmd.Err(); err != nil {
recordError(ctx, span, err)
}
span.End()
return nil
}
func (TracingHook) BeforeProcessPipeline(ctx context.Context, cmds []redis.Cmder) (context.Context, error) {
if !trace.SpanFromContext(ctx).IsRecording() {
return ctx, nil
}
summary, cmdsString := rediscmd.CmdsString(cmds)
ctx, span := tracer.Start(ctx, "pipeline "+summary)
span.SetAttributes(
2021-03-04 04:43:10 +03:00
attribute.String("db.system", "redis"),
attribute.Int("db.redis.num_cmd", len(cmds)),
attribute.String("db.statement", cmdsString),
2020-10-21 15:19:27 +03:00
)
return ctx, nil
}
func (TracingHook) AfterProcessPipeline(ctx context.Context, cmds []redis.Cmder) error {
span := trace.SpanFromContext(ctx)
if err := cmds[0].Err(); err != nil {
recordError(ctx, span, err)
}
span.End()
return nil
}
func recordError(ctx context.Context, span trace.Span, err error) {
if err != redis.Nil {
2020-11-21 10:56:52 +03:00
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
2020-10-21 15:19:27 +03:00
}
}