Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add support for custome labels #289

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 38 additions & 2 deletions query.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package otelsql
import (
"context"
"database/sql/driver"

"go.opentelemetry.io/otel/attribute"
)

const (
Expand All @@ -24,11 +26,41 @@ func skippedQueryContext(_ context.Context, _ string, _ []driver.NamedValue) (dr
return nil, driver.ErrSkip
}

// add custome labels to metrics and traces
type ctxKey string

const (
meterCtxKey ctxKey = "meterCtxKey"
tracerCtxKey ctxKey = "traceCtxKey"
)

func getLabels(ctx context.Context, key ctxKey) []attribute.KeyValue {
labels, ok := ctx.Value(key).([]attribute.KeyValue)
if !ok || labels == nil {
labels = make([]attribute.KeyValue, 0)
}
return labels
}

func addLabels(ctx context.Context, key ctxKey, labels ...attribute.KeyValue) context.Context {
new := append(getLabels(ctx, key), labels...)
return context.WithValue(ctx, key, new)
}

func AddMeterLabels(ctx context.Context, labels ...attribute.KeyValue) context.Context {
return addLabels(ctx, meterCtxKey, labels...)
}

func AddTracerLabels(ctx context.Context, labels ...attribute.KeyValue) context.Context {
return addLabels(ctx, tracerCtxKey, labels...)
}

// queryStats records metrics for query.
func queryStats(r methodRecorder, method string) queryContextFuncMiddleware {
return func(next queryContextFunc) queryContextFunc {
return func(ctx context.Context, query string, args []driver.NamedValue) (result driver.Rows, err error) {
end := r.Record(ctx, method)
labels := getLabels(ctx, meterCtxKey)
end := r.Record(ctx, method, labels...)

defer func() {
end(err)
Expand All @@ -49,7 +81,11 @@ func queryTrace(t methodTracer, traceQuery queryTracer, method string) queryCont
ctx, end := t.Trace(ctx, method)

defer func() {
end(err, traceQuery(ctx, query, args)...)
labels := append(
getLabels(ctx, tracerCtxKey),
traceQuery(ctx, query, args)...,
)
end(err, labels...)
}()

result, err = next(ctx, query, args)
Expand Down