Compare commits

..

No commits in common. "master" and "v4.0.0" have entirely different histories.

13 changed files with 2344 additions and 2255 deletions

9
.gitignore vendored
View File

@ -4,7 +4,6 @@
*.dll *.dll
*.so *.so
*.dylib *.dylib
bin
# Test binary, built with `go test -c` # Test binary, built with `go test -c`
*.test *.test
@ -14,11 +13,3 @@ bin
# Dependency directories (remove the comment below to include it) # Dependency directories (remove the comment below to include it)
# vendor/ # vendor/
# Go workspace file
go.work
# General
.DS_Store
.idea
.vscode

View File

@ -4,7 +4,6 @@ import (
"database/sql/driver" "database/sql/driver"
"errors" "errors"
"fmt" "fmt"
"runtime"
) )
//go:generate sh -c "go run gen.go > wrap_gen.go" //go:generate sh -c "go run gen.go > wrap_gen.go"
@ -32,20 +31,7 @@ func namedValueToLabels(named []driver.NamedValue) []interface{} {
} else { } else {
name = fmt.Sprintf("$%d", param.Ordinal) name = fmt.Sprintf("$%d", param.Ordinal)
} }
largs = append(largs, fmt.Sprintf("%s=%v", name, param.Value)) largs = append(largs, fmt.Sprintf("%s=%s", name, param.Value))
} }
return largs return largs
} }
// getCallerName get the name of the function A where A() -> B() -> GetFunctionCallerName()
func getCallerName() string {
pc, _, _, ok := runtime.Caller(3)
details := runtime.FuncForPC(pc)
var callerName string
if ok && details != nil {
callerName = details.Name()
} else {
callerName = labelUnknown
}
return callerName
}

117
conn.go
View File

@ -6,7 +6,6 @@ import (
"fmt" "fmt"
"time" "time"
requestid "go.unistack.org/micro-wrapper-requestid/v4"
"go.unistack.org/micro/v4/tracer" "go.unistack.org/micro/v4/tracer"
) )
@ -16,9 +15,9 @@ var (
_ driver.ConnPrepareContext = (*wrapperConn)(nil) _ driver.ConnPrepareContext = (*wrapperConn)(nil)
_ driver.Pinger = (*wrapperConn)(nil) _ driver.Pinger = (*wrapperConn)(nil)
_ driver.Validator = (*wrapperConn)(nil) _ driver.Validator = (*wrapperConn)(nil)
_ driver.Queryer = (*wrapperConn)(nil) // nolint:staticcheck _ driver.Queryer = (*wrapperConn)(nil)
_ driver.QueryerContext = (*wrapperConn)(nil) _ driver.QueryerContext = (*wrapperConn)(nil)
_ driver.Execer = (*wrapperConn)(nil) // nolint:staticcheck _ driver.Execer = (*wrapperConn)(nil)
_ driver.ExecerContext = (*wrapperConn)(nil) _ driver.ExecerContext = (*wrapperConn)(nil)
// _ driver.Connector // _ driver.Connector
// _ driver.Driver // _ driver.Driver
@ -58,7 +57,7 @@ func (w *wrapperConn) Close() error {
w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te) w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te)
if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) { if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) {
w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "Close", getCallerName(), td, err)...).Log(ctx, w.opts.LoggerLevel) w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "Close", labelUnknown, td, err)...).Log(ctx, w.opts.LoggerLevel)
} }
return err return err
@ -83,7 +82,7 @@ func (w *wrapperConn) Begin() (driver.Tx, error) {
w.opts.Meter.Summary(meterRequestLatencyMicroseconds, labels...).Update(te) w.opts.Meter.Summary(meterRequestLatencyMicroseconds, labels...).Update(te)
w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te) w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te)
if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) { if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) {
w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "Begin", getCallerName(), td, err)...).Log(ctx, w.opts.LoggerLevel) w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "Begin", labelUnknown, td, err)...).Log(ctx, w.opts.LoggerLevel)
} }
return nil, err return nil, err
} }
@ -91,7 +90,7 @@ func (w *wrapperConn) Begin() (driver.Tx, error) {
w.opts.Meter.Summary(meterRequestLatencyMicroseconds, labels...).Update(te) w.opts.Meter.Summary(meterRequestLatencyMicroseconds, labels...).Update(te)
w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te) w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te)
if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) { if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) {
w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "Begin", getCallerName(), td, err)...).Log(ctx, w.opts.LoggerLevel) w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "Begin", labelUnknown, td, err)...).Log(ctx, w.opts.LoggerLevel)
} }
return &wrapperTx{tx: tx, opts: w.opts, ctx: ctx}, nil return &wrapperTx{tx: tx, opts: w.opts, ctx: ctx}, nil
@ -99,12 +98,13 @@ func (w *wrapperConn) Begin() (driver.Tx, error) {
// BeginTx implements driver.ConnBeginTx BeginTx // BeginTx implements driver.ConnBeginTx BeginTx
func (w *wrapperConn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { func (w *wrapperConn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) {
nctx, span := w.opts.Tracer.Start(ctx, "sdk.database", tracer.WithSpanKind(tracer.SpanKindClient)) nctx, span := w.opts.Tracer.Start(ctx, "Transaction")
span.AddLabels("db.method", "BeginTx") span.AddLabels("method", "BeginTx")
name := getQueryName(ctx) name := getQueryName(ctx)
span.AddLabels("db.statement", name) if name != "" {
if id, ok := ctx.Value(requestid.XRequestIDKey).(string); ok { span.AddLabels("query", name)
span.AddLabels("x-request-id", id) } else {
name = labelUnknown
} }
labels := []string{labelMethod, "BeginTx", labelQuery, name} labels := []string{labelMethod, "BeginTx", labelQuery, name}
@ -121,15 +121,16 @@ func (w *wrapperConn) BeginTx(ctx context.Context, opts driver.TxOptions) (drive
w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelFailure)...).Inc() w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelFailure)...).Inc()
w.opts.Meter.Summary(meterRequestLatencyMicroseconds, labels...).Update(te) w.opts.Meter.Summary(meterRequestLatencyMicroseconds, labels...).Update(te)
w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te) w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te)
span.SetStatus(tracer.SpanStatusError, err.Error()) span.AddLabels("error", true)
span.AddLabels("err", err.Error())
if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) { if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) {
w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "BeginTx", getCallerName(), td, err)...).Log(ctx, w.opts.LoggerLevel) w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "BeginTx", name, td, err)...).Log(ctx, w.opts.LoggerLevel)
} }
return nil, err return nil, err
} }
w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelSuccess)...).Inc() w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelSuccess)...).Inc()
if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) { if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) {
w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "BeginTx", getCallerName(), td, err)...).Log(ctx, w.opts.LoggerLevel) w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "BeginTx", name, td, err)...).Log(ctx, w.opts.LoggerLevel)
} }
return &wrapperTx{tx: tx, opts: w.opts, ctx: ctx, span: span}, nil return &wrapperTx{tx: tx, opts: w.opts, ctx: ctx, span: span}, nil
} }
@ -143,7 +144,7 @@ func (w *wrapperConn) Prepare(query string) (driver.Stmt, error) {
ctx = context.Background() ctx = context.Background()
} }
labels := []string{labelMethod, "Prepare", labelQuery, getCallerName()} labels := []string{labelMethod, "Prepare", labelQuery, labelUnknown}
ts := time.Now() ts := time.Now()
stmt, err := w.conn.Prepare(query) stmt, err := w.conn.Prepare(query)
td := time.Since(ts) td := time.Since(ts)
@ -152,8 +153,9 @@ func (w *wrapperConn) Prepare(query string) (driver.Stmt, error) {
w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelFailure)...).Inc() w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelFailure)...).Inc()
w.opts.Meter.Summary(meterRequestLatencyMicroseconds, labels...).Update(te) w.opts.Meter.Summary(meterRequestLatencyMicroseconds, labels...).Update(te)
w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te) w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te)
if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) { if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) {
w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "Prepare", getCallerName(), td, err)...).Log(ctx, w.opts.LoggerLevel) w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "Prepare", labelUnknown, td, err)...).Log(ctx, w.opts.LoggerLevel)
} }
return nil, err return nil, err
} }
@ -162,7 +164,7 @@ func (w *wrapperConn) Prepare(query string) (driver.Stmt, error) {
w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te) w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te)
if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) { if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) {
w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "Prepare", getCallerName(), td, err)...).Log(ctx, w.opts.LoggerLevel) w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "Prepare", labelUnknown, td, err)...).Log(ctx, w.opts.LoggerLevel)
} }
return wrapStmt(stmt, query, w.opts), nil return wrapStmt(stmt, query, w.opts), nil
@ -172,18 +174,19 @@ func (w *wrapperConn) Prepare(query string) (driver.Stmt, error) {
func (w *wrapperConn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) { func (w *wrapperConn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) {
var nctx context.Context var nctx context.Context
var span tracer.Span var span tracer.Span
if w.ctx != nil { if w.ctx != nil {
nctx, span = w.opts.Tracer.Start(w.ctx, "sdk.database", tracer.WithSpanKind(tracer.SpanKindClient)) nctx, span = w.opts.Tracer.Start(w.ctx, "PrepareContext")
} else { } else {
nctx, span = w.opts.Tracer.Start(ctx, "sdk.database", tracer.WithSpanKind(tracer.SpanKindClient)) nctx, span = w.opts.Tracer.Start(ctx, "PrepareContext")
} }
span.AddLabels("db.method", "PrepareContext") span.AddLabels("method", "PrepareContext")
name := getQueryName(ctx) name := getQueryName(ctx)
span.AddLabels("db.statement", name) if name != "" {
if id, ok := ctx.Value(requestid.XRequestIDKey).(string); ok { span.AddLabels("query", name)
span.AddLabels("x-request-id", id) } else {
name = labelUnknown
} }
labels := []string{labelMethod, "PrepareContext", labelQuery, name} labels := []string{labelMethod, "PrepareContext", labelQuery, name}
conn, ok := w.conn.(driver.ConnPrepareContext) conn, ok := w.conn.(driver.ConnPrepareContext)
if !ok { if !ok {
@ -198,9 +201,10 @@ func (w *wrapperConn) PrepareContext(ctx context.Context, query string) (driver.
w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelFailure)...).Inc() w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelFailure)...).Inc()
w.opts.Meter.Summary(meterRequestLatencyMicroseconds, labels...).Update(te) w.opts.Meter.Summary(meterRequestLatencyMicroseconds, labels...).Update(te)
w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te) w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te)
span.SetStatus(tracer.SpanStatusError, err.Error()) span.AddLabels("error", true)
span.AddLabels("err", err.Error())
if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) { if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) {
w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "PrepareContext", getCallerName(), td, err)...).Log(ctx, w.opts.LoggerLevel) w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "PrepareContext", name, td, err)...).Log(ctx, w.opts.LoggerLevel)
} }
return nil, err return nil, err
} }
@ -208,7 +212,7 @@ func (w *wrapperConn) PrepareContext(ctx context.Context, query string) (driver.
w.opts.Meter.Summary(meterRequestLatencyMicroseconds, labels...).Update(te) w.opts.Meter.Summary(meterRequestLatencyMicroseconds, labels...).Update(te)
w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te) w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te)
if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) { if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) {
w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "PrepareContext", getCallerName(), td, err)...).Log(ctx, w.opts.LoggerLevel) w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "PrepareContext", name, td, err)...).Log(ctx, w.opts.LoggerLevel)
} }
return wrapStmt(stmt, query, w.opts), nil return wrapStmt(stmt, query, w.opts), nil
@ -222,7 +226,7 @@ func (w *wrapperConn) Exec(query string, args []driver.Value) (driver.Result, er
} else { } else {
ctx = context.Background() ctx = context.Background()
} }
labels := []string{labelMethod, "Exec", labelQuery, getCallerName()} labels := []string{labelMethod, "Exec", labelQuery, labelUnknown}
// nolint:staticcheck // nolint:staticcheck
conn, ok := w.conn.(driver.Execer) conn, ok := w.conn.(driver.Execer)
@ -242,7 +246,7 @@ func (w *wrapperConn) Exec(query string, args []driver.Value) (driver.Result, er
w.opts.Meter.Summary(meterRequestLatencyMicroseconds, labels...).Update(te) w.opts.Meter.Summary(meterRequestLatencyMicroseconds, labels...).Update(te)
w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te) w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te)
if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) { if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) {
w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "Exec", getCallerName(), td, err)...).Log(ctx, w.opts.LoggerLevel) w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "Exec", labelUnknown, td, err)...).Log(ctx, w.opts.LoggerLevel)
} }
return res, err return res, err
} }
@ -253,21 +257,23 @@ func (w *wrapperConn) ExecContext(ctx context.Context, query string, args []driv
var span tracer.Span var span tracer.Span
if w.ctx != nil { if w.ctx != nil {
nctx, span = w.opts.Tracer.Start(w.ctx, "sdk.database", tracer.WithSpanKind(tracer.SpanKindClient)) nctx, span = w.opts.Tracer.Start(w.ctx, "ExecContext")
} else { } else {
nctx, span = w.opts.Tracer.Start(ctx, "sdk.database", tracer.WithSpanKind(tracer.SpanKindClient)) nctx, span = w.opts.Tracer.Start(ctx, "ExecContext")
} }
span.AddLabels("db.method", "ExecContext") span.AddLabels("method", "ExecContext")
name := getQueryName(ctx) name := getQueryName(ctx)
span.AddLabels("db.statement", name) if name != "" {
if id, ok := ctx.Value(requestid.XRequestIDKey).(string); ok { span.AddLabels("query", name)
span.AddLabels("x-request-id", id) } else {
name = labelUnknown
} }
defer span.Finish() defer span.Finish()
if len(args) > 0 { if len(args) > 0 {
span.AddLabels("db.args", fmt.Sprintf("%v", namedValueToLabels(args))) span.AddLabels("args", fmt.Sprintf("%v", namedValueToLabels(args)))
} }
labels := []string{labelMethod, "ExecContext", labelQuery, name} labels := []string{labelMethod, "ExecContext", labelQuery, name}
fmt.Printf("EXECCONTETX args %#+v\n", args)
conn, ok := w.conn.(driver.ExecerContext) conn, ok := w.conn.(driver.ExecerContext)
if !ok { if !ok {
@ -281,7 +287,8 @@ func (w *wrapperConn) ExecContext(ctx context.Context, query string, args []driv
te := td.Seconds() te := td.Seconds()
if err != nil { if err != nil {
w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelFailure)...).Inc() w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelFailure)...).Inc()
span.SetStatus(tracer.SpanStatusError, err.Error()) span.AddLabels("error", true)
span.AddLabels("err", err.Error())
} else { } else {
w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelSuccess)...).Inc() w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelSuccess)...).Inc()
} }
@ -289,7 +296,7 @@ func (w *wrapperConn) ExecContext(ctx context.Context, query string, args []driv
w.opts.Meter.Summary(meterRequestLatencyMicroseconds, labels...).Update(te) w.opts.Meter.Summary(meterRequestLatencyMicroseconds, labels...).Update(te)
w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te) w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te)
if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) { if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) {
w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "ExecContext", getCallerName(), td, err)...).Log(ctx, w.opts.LoggerLevel) w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "ExecContext", name, td, err)...).Log(ctx, w.opts.LoggerLevel)
} }
return res, err return res, err
@ -311,9 +318,9 @@ func (w *wrapperConn) Ping(ctx context.Context) error {
var nctx context.Context var nctx context.Context
var span tracer.Span var span tracer.Span
if w.ctx != nil { if w.ctx != nil {
nctx, span = w.opts.Tracer.Start(w.ctx, "sdk.database", tracer.WithSpanKind(tracer.SpanKindClient)) nctx, span = w.opts.Tracer.Start(w.ctx, "Ping")
} else { } else {
nctx, span = w.opts.Tracer.Start(ctx, "sdk.database", tracer.WithSpanKind(tracer.SpanKindClient)) nctx, span = w.opts.Tracer.Start(ctx, "Ping")
} }
defer span.Finish() defer span.Finish()
labels := []string{labelMethod, "Ping"} labels := []string{labelMethod, "Ping"}
@ -323,9 +330,10 @@ func (w *wrapperConn) Ping(ctx context.Context) error {
te := td.Seconds() te := td.Seconds()
if err != nil { if err != nil {
w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelFailure)...).Inc() w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelFailure)...).Inc()
span.SetStatus(tracer.SpanStatusError, err.Error()) span.AddLabels("error", true)
span.AddLabels("err", err.Error())
if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) { if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) {
w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "Ping", getCallerName(), td, err)...).Log(ctx, w.opts.LoggerLevel) w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "Ping", labelUnknown, td, err)...).Log(ctx, w.opts.LoggerLevel)
} }
return err return err
} else { } else {
@ -351,7 +359,7 @@ func (w *wrapperConn) Query(query string, args []driver.Value) (driver.Rows, err
return nil, driver.ErrSkip return nil, driver.ErrSkip
} }
labels := []string{labelMethod, "Query", labelQuery, getCallerName()} labels := []string{labelMethod, "Query", labelQuery, labelUnknown}
ts := time.Now() ts := time.Now()
rows, err := conn.Query(query, args) rows, err := conn.Query(query, args)
td := time.Since(ts) td := time.Since(ts)
@ -364,7 +372,7 @@ func (w *wrapperConn) Query(query string, args []driver.Value) (driver.Rows, err
w.opts.Meter.Summary(meterRequestLatencyMicroseconds, labels...).Update(te) w.opts.Meter.Summary(meterRequestLatencyMicroseconds, labels...).Update(te)
w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te) w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te)
if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) { if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) {
w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "Query", getCallerName(), td, err)...).Log(ctx, w.opts.LoggerLevel) w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "Query", labelUnknown, td, err)...).Log(ctx, w.opts.LoggerLevel)
} }
return rows, err return rows, err
} }
@ -373,21 +381,21 @@ func (w *wrapperConn) Query(query string, args []driver.Value) (driver.Rows, err
func (w *wrapperConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) { func (w *wrapperConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) {
var nctx context.Context var nctx context.Context
var span tracer.Span var span tracer.Span
if w.ctx != nil { if w.ctx != nil {
nctx, span = w.opts.Tracer.Start(w.ctx, "sdk.database", tracer.WithSpanKind(tracer.SpanKindClient)) nctx, span = w.opts.Tracer.Start(w.ctx, "QueryContext")
} else { } else {
nctx, span = w.opts.Tracer.Start(ctx, "sdk.database", tracer.WithSpanKind(tracer.SpanKindClient)) nctx, span = w.opts.Tracer.Start(ctx, "QueryContext")
} }
span.AddLabels("db.method", "QueryContext") span.AddLabels("method", "QueryContext")
name := getQueryName(ctx) name := getQueryName(ctx)
span.AddLabels("db.statement", name) if name != "" {
if id, ok := ctx.Value(requestid.XRequestIDKey).(string); ok { span.AddLabels("query", name)
span.AddLabels("x-request-id", id) } else {
name = labelUnknown
} }
defer span.Finish() defer span.Finish()
if len(args) > 0 { if len(args) > 0 {
span.AddLabels("db.args", fmt.Sprintf("%v", namedValueToLabels(args))) span.AddLabels("args", fmt.Sprintf("%v", namedValueToLabels(args)))
} }
labels := []string{labelMethod, "QueryContext", labelQuery, name} labels := []string{labelMethod, "QueryContext", labelQuery, name}
conn, ok := w.conn.(driver.QueryerContext) conn, ok := w.conn.(driver.QueryerContext)
@ -401,14 +409,15 @@ func (w *wrapperConn) QueryContext(ctx context.Context, query string, args []dri
te := td.Seconds() te := td.Seconds()
if err != nil { if err != nil {
w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelFailure)...).Inc() w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelFailure)...).Inc()
span.SetStatus(tracer.SpanStatusError, err.Error()) span.AddLabels("error", true)
span.AddLabels("err", err.Error())
} else { } else {
w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelSuccess)...).Inc() w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelSuccess)...).Inc()
} }
w.opts.Meter.Summary(meterRequestLatencyMicroseconds, labels...).Update(te) w.opts.Meter.Summary(meterRequestLatencyMicroseconds, labels...).Update(te)
w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te) w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te)
if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) { if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) {
w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "QueryContext", getCallerName(), td, err)...).Log(ctx, w.opts.LoggerLevel) w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "QueryContext", name, td, err)...).Log(ctx, w.opts.LoggerLevel)
} }
return rows, err return rows, err

View File

@ -24,9 +24,16 @@ type conn interface {
// wrapperDriver defines a wrapper for driver.Driver // wrapperDriver defines a wrapper for driver.Driver
type wrapperDriver struct { type wrapperDriver struct {
driver driver.Driver
connector driver.Connector
opts Options
ctx context.Context
}
type wrapperConnector struct {
driver driver.Driver driver driver.Driver
name string
opts Options opts Options
ctx context.Context
} }
// NewWrapper creates and returns a new SQL driver with passed capabilities // NewWrapper creates and returns a new SQL driver with passed capabilities
@ -34,26 +41,17 @@ func NewWrapper(d driver.Driver, opts ...Option) driver.Driver {
return &wrapperDriver{driver: d, opts: NewOptions(opts...), ctx: context.Background()} return &wrapperDriver{driver: d, opts: NewOptions(opts...), ctx: context.Background()}
} }
type wrappedConnector struct { /*
connector driver.Connector
name string
opts Options
ctx context.Context
}
func NewWrapperConnector(c driver.Connector, opts ...Option) driver.Connector {
return &wrappedConnector{connector: c, opts: NewOptions(opts...), ctx: context.Background()}
}
// Connect implements driver.Driver Connect // Connect implements driver.Driver Connect
func (w *wrappedConnector) Connect(ctx context.Context) (driver.Conn, error) { func (w *wrapperConnector) Connect(ctx context.Context) (driver.Conn, error) {
return w.connector.Connect(ctx) return w.driver.Connect(ctx)
} }
// Driver implements driver.Driver Driver // Driver implements driver.Driver Driver
func (w *wrappedConnector) Driver() driver.Driver { func (w *wrapperConnector) Driver() driver.Driver {
return w.connector.Driver() return w.driver
} }
*/
/* /*
// Connect implements driver.Driver OpenConnector // Connect implements driver.Driver OpenConnector
@ -80,7 +78,7 @@ func (w *wrapperDriver) Open(name string) (driver.Conn, error) {
td := time.Since(ts) td := time.Since(ts)
if w.opts.LoggerEnabled { if w.opts.LoggerEnabled {
w.opts.Logger.Fields(w.opts.LoggerObserver(w.ctx, "Open", getCallerName(), td, err)...).Log(w.ctx, w.opts.LoggerLevel) w.opts.Logger.Fields(w.opts.LoggerObserver(w.ctx, "Open", labelUnknown, td, err)...).Log(w.ctx, w.opts.LoggerLevel)
} }
if err != nil { if err != nil {
return nil, err return nil, err

16
gen.go
View File

@ -66,7 +66,7 @@ func main() {
continue continue
} }
h := getHash(ifaces) h := getHash(ifaces)
b.WriteString(fmt.Sprintf("\tif _, ok := dc.(wrapConn%04d_%s); ok {\n", n, h)) b.WriteString(fmt.Sprintf("\tif v, ok := dc.(wrapConn%04d_%s); ok {\n", n, h))
b.WriteString("\treturn struct {\n") b.WriteString("\treturn struct {\n")
b.WriteString("\t\tdriver.Conn\n") b.WriteString("\t\tdriver.Conn\n")
b.WriteString(fmt.Sprintf("\t\t\t%s", strings.Join(ifaces, "\n\t\t\t"))) b.WriteString(fmt.Sprintf("\t\t\t%s", strings.Join(ifaces, "\n\t\t\t")))
@ -74,14 +74,14 @@ func main() {
for idx := range ifaces { for idx := range ifaces {
if idx > 0 { if idx > 0 {
b.WriteString(", ") b.WriteString(", ")
b.WriteString("c") b.WriteString("v")
} else if idx == 0 { } else if idx == 0 {
b.WriteString("c") b.WriteString("c")
} else { } else {
b.WriteString("c") b.WriteString("v")
} }
} }
b.WriteString(", c}\n") b.WriteString(", v}\n")
b.WriteString("}\n\n") b.WriteString("}\n\n")
} }
b.WriteString("return c\n") b.WriteString("return c\n")
@ -112,7 +112,7 @@ func main() {
continue continue
} }
h := getHash(ifaces) h := getHash(ifaces)
b.WriteString(fmt.Sprintf("\tif _, ok := stmt.(wrapStmt%04d_%s); ok {\n", n, h)) b.WriteString(fmt.Sprintf("\tif v, ok := stmt.(wrapStmt%04d_%s); ok {\n", n, h))
b.WriteString("\treturn struct {\n") b.WriteString("\treturn struct {\n")
b.WriteString("\t\tdriver.Stmt\n") b.WriteString("\t\tdriver.Stmt\n")
b.WriteString(fmt.Sprintf("\t\t\t%s", strings.Join(ifaces, "\n\t\t\t"))) b.WriteString(fmt.Sprintf("\t\t\t%s", strings.Join(ifaces, "\n\t\t\t")))
@ -120,14 +120,14 @@ func main() {
for idx := range ifaces { for idx := range ifaces {
if idx > 0 { if idx > 0 {
b.WriteString(", ") b.WriteString(", ")
b.WriteString("c") b.WriteString("v")
} else if idx == 0 { } else if idx == 0 {
b.WriteString("c") b.WriteString("c")
} else { } else {
b.WriteString("c") b.WriteString("v")
} }
} }
b.WriteString(", c}\n") b.WriteString(", v}\n")
b.WriteString("}\n\n") b.WriteString("}\n\n")
} }
b.WriteString("return c\n") b.WriteString("return c\n")

7
go.mod
View File

@ -1,8 +1,5 @@
module go.unistack.org/micro-wrapper-sql/v4 module go.unistack.org/micro-wrapper-sql/v4
go 1.20 go 1.19
require ( require go.unistack.org/micro/v4 v4.0.3
go.unistack.org/micro-wrapper-requestid/v4 v4.0.3
go.unistack.org/micro/v4 v4.0.8
)

6
go.sum
View File

@ -1,4 +1,2 @@
go.unistack.org/micro-wrapper-requestid/v4 v4.0.3 h1:LhloK8yLLsov4XiKw9i20wdBUfvWCG1TaBNgNVtNa8Q= go.unistack.org/micro/v4 v4.0.3 h1:AFr21ua3IrkuxH26kNYVrs7Kpsrm+4aylE/PfjLdCWM=
go.unistack.org/micro-wrapper-requestid/v4 v4.0.3/go.mod h1:vRIkCMyhbBVus1xQlr/Fef65n07znrBGkpSCpjkEiqk= go.unistack.org/micro/v4 v4.0.3/go.mod h1:+wBa98rSf+mRXb/MuSVFPXtDrqN0k8rzPQiC8wRCwCo=
go.unistack.org/micro/v4 v4.0.8 h1:D5n18+fhyRjJkKSPdIcW1ratWUuzy9TzrS5ud/qImWg=
go.unistack.org/micro/v4 v4.0.8/go.mod h1:QT3gOIE4qGgBiQGm2Pad/62Sl5R53QfrgYHD448aX14=

View File

@ -2,8 +2,6 @@ package wrapper
import ( import (
"context" "context"
"database/sql"
"errors"
"fmt" "fmt"
"time" "time"
@ -19,8 +17,8 @@ var (
DefaultMeterMetricPrefix = "micro_sql_" DefaultMeterMetricPrefix = "micro_sql_"
// DefaultLoggerObserver used to prepare labels for logger // DefaultLoggerObserver used to prepare labels for logger
DefaultLoggerObserver = func(ctx context.Context, method string, query string, td time.Duration, err error) []interface{} { DefaultLoggerObserver = func(ctx context.Context, method string, query string, td time.Duration, err error) []interface{} {
labels := []interface{}{"db.method", method, "took", fmt.Sprintf("%v", td)} labels := []interface{}{"method", method, "took", fmt.Sprintf("%v", td)}
if err != nil && !errors.Is(err, sql.ErrNoRows) { if err != nil {
labels = append(labels, "error", err.Error()) labels = append(labels, "error", err.Error())
} }
if query != labelUnknown { if query != labelUnknown {
@ -31,23 +29,23 @@ var (
) )
var ( var (
MaxOpenConnections = "max_open_conn" MaxOpenConnections = "max_open_connections"
OpenConnections = "open_conn" OpenConnections = "open_connections"
InuseConnections = "inuse_conn" InuseConnections = "inuse_connections"
IdleConnections = "idle_conn" IdleConnections = "idle_connections"
WaitConnections = "waited_conn" WaitConnections = "wait_connections"
BlockedSeconds = "blocked_seconds" BlockedSeconds = "blocked_seconds"
MaxIdleClosed = "max_idle_closed" MaxIdleClosed = "max_idle_closed"
MaxIdletimeClosed = "closed_max_idle" MaxIdletimeClosed = "max_idletime_closed"
MaxLifetimeClosed = "closed_max_lifetime" MaxLifetimeClosed = "max_lifetime_closed"
meterRequestTotal = "request_total" meterRequestTotal = "request_total"
meterRequestLatencyMicroseconds = "latency_microseconds" meterRequestLatencyMicroseconds = "request_latency_microseconds"
meterRequestDurationSeconds = "request_duration_seconds" meterRequestDurationSeconds = "request_duration_seconds"
labelUnknown = "unknown" labelUnknown = "unknown"
labelQuery = "db_statement" labelQuery = "query"
labelMethod = "db_method" labelMethod = "method"
labelStatus = "status" labelStatus = "status"
labelSuccess = "success" labelSuccess = "success"
labelFailure = "failure" labelFailure = "failure"
@ -80,7 +78,7 @@ func NewOptions(opts ...Option) Options {
Tracer: tracer.DefaultTracer, Tracer: tracer.DefaultTracer,
MeterStatsInterval: DefaultMeterStatsInterval, MeterStatsInterval: DefaultMeterStatsInterval,
MeterMetricPrefix: DefaultMeterMetricPrefix, MeterMetricPrefix: DefaultMeterMetricPrefix,
LoggerLevel: logger.ErrorLevel, LoggerLevel: logger.DebugLevel,
LoggerObserver: DefaultLoggerObserver, LoggerObserver: DefaultLoggerObserver,
} }
for _, o := range opts { for _, o := range opts {
@ -179,8 +177,8 @@ func QueryName(ctx context.Context, name string) context.Context {
} }
func getQueryName(ctx context.Context) string { func getQueryName(ctx context.Context) string {
if v, ok := ctx.Value(queryNameKey{}).(string); ok && v != labelUnknown { if v, ok := ctx.Value(queryNameKey{}).(string); ok {
return v return v
} }
return getCallerName() return ""
} }

View File

@ -1,4 +1,4 @@
package wrapper // import "go.unistack.org/micro-wrapper-sql/v4" package wrapper // import "go.unistack.org/micro-wrapper-sql-1/v3"
import ( import (
"context" "context"

88
stmt.go
View File

@ -6,7 +6,6 @@ import (
"fmt" "fmt"
"time" "time"
requestid "go.unistack.org/micro-wrapper-requestid/v4"
"go.unistack.org/micro/v4/tracer" "go.unistack.org/micro/v4/tracer"
) )
@ -47,7 +46,7 @@ func (w *wrapperStmt) Close() error {
w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te) w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te)
if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) { if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) {
w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "Close", getCallerName(), td, err)).Log(ctx, w.opts.LoggerLevel) w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "Close", labelUnknown, td, err)...).Log(ctx, w.opts.LoggerLevel)
} }
return err return err
} }
@ -76,7 +75,8 @@ func (w *wrapperStmt) Exec(args []driver.Value) (driver.Result, error) {
} }
labels := []string{labelMethod, "Exec"} labels := []string{labelMethod, "Exec"}
ts := time.Now() ts := time.Now()
res, err := w.stmt.Exec(args) // nolint:staticcheck // nolint:staticcheck
res, err := w.stmt.Exec(args)
td := time.Since(ts) td := time.Since(ts)
te := td.Seconds() te := td.Seconds()
if err != nil { if err != nil {
@ -88,7 +88,7 @@ func (w *wrapperStmt) Exec(args []driver.Value) (driver.Result, error) {
w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te) w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te)
if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) { if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) {
w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "Exec", getCallerName(), td, err)).Log(ctx, w.opts.LoggerLevel) w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "Exec", labelUnknown, td, err)...).Log(ctx, w.opts.LoggerLevel)
} }
return res, err return res, err
@ -104,7 +104,8 @@ func (w *wrapperStmt) Query(args []driver.Value) (driver.Rows, error) {
} }
labels := []string{labelMethod, "Query"} labels := []string{labelMethod, "Query"}
ts := time.Now() ts := time.Now()
rows, err := w.stmt.Query(args) // nolint:staticcheck // nolint:staticcheck
rows, err := w.stmt.Query(args)
td := time.Since(ts) td := time.Since(ts)
te := td.Seconds() te := td.Seconds()
if err != nil { if err != nil {
@ -116,40 +117,31 @@ func (w *wrapperStmt) Query(args []driver.Value) (driver.Rows, error) {
w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te) w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te)
if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) { if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) {
w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "Query", getCallerName(), td, err)).Log(ctx, w.opts.LoggerLevel) w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "Query", labelUnknown, td, err)...).Log(ctx, w.opts.LoggerLevel)
} }
return rows, err return rows, err
} }
// ColumnConverter implements driver.ColumnConverter
func (w *wrapperStmt) ColumnConverter(idx int) driver.ValueConverter {
s, ok := w.stmt.(driver.ColumnConverter) // nolint:staticcheck
if !ok {
return nil
}
return s.ColumnConverter(idx)
}
// ExecContext implements driver.StmtExecContext ExecContext // ExecContext implements driver.StmtExecContext ExecContext
func (w *wrapperStmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) { func (w *wrapperStmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) {
var nctx context.Context var nctx context.Context
var span tracer.Span var span tracer.Span
if w.ctx != nil { if w.ctx != nil {
nctx, span = w.opts.Tracer.Start(w.ctx, "sdk.database", tracer.WithSpanKind(tracer.SpanKindClient)) nctx, span = w.opts.Tracer.Start(w.ctx, "ExecContext")
} else { } else {
nctx, span = w.opts.Tracer.Start(ctx, "sdk.database", tracer.WithSpanKind(tracer.SpanKindClient)) nctx, span = w.opts.Tracer.Start(ctx, "ExecContext")
} }
span.AddLabels("db.method", "ExecContext") span.AddLabels("method", "ExecContext")
name := getQueryName(ctx) name := getQueryName(ctx)
span.AddLabels("db.statement", name) if name != "" {
span.AddLabels("query", name)
} else {
name = labelUnknown
}
defer span.Finish() defer span.Finish()
if len(args) > 0 { if len(args) > 0 {
span.AddLabels("db.args", fmt.Sprintf("%v", namedValueToLabels(args))) span.AddLabels("args", fmt.Sprintf("%v", namedValueToLabels(args)))
}
if id, ok := ctx.Value(requestid.XRequestIDKey).(string); ok {
span.AddLabels("x-request-id", id)
} }
labels := []string{labelMethod, "ExecContext", labelQuery, name} labels := []string{labelMethod, "ExecContext", labelQuery, name}
@ -160,7 +152,8 @@ func (w *wrapperStmt) ExecContext(ctx context.Context, args []driver.NamedValue)
te := td.Seconds() te := td.Seconds()
if err != nil { if err != nil {
w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelFailure)...).Inc() w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelFailure)...).Inc()
span.SetStatus(tracer.SpanStatusError, err.Error()) span.AddLabels("error", true)
span.AddLabels("err", err.Error())
} else { } else {
w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelSuccess)...).Inc() w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelSuccess)...).Inc()
} }
@ -168,7 +161,7 @@ func (w *wrapperStmt) ExecContext(ctx context.Context, args []driver.NamedValue)
w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te) w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te)
if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) { if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) {
w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "ExecContext", name, td, err)).Log(ctx, w.opts.LoggerLevel) w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "ExecContext", name, td, err)...).Log(ctx, w.opts.LoggerLevel)
} }
return res, err return res, err
} }
@ -176,10 +169,11 @@ func (w *wrapperStmt) ExecContext(ctx context.Context, args []driver.NamedValue)
values, err := namedValueToValue(args) values, err := namedValueToValue(args)
if err != nil { if err != nil {
w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelFailure)...).Inc() w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelFailure)...).Inc()
span.SetStatus(tracer.SpanStatusError, err.Error()) span.AddLabels("error", true)
span.AddLabels("err", err.Error())
if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) { if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) {
w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "ExecContext", name, 0, err)).Log(ctx, w.opts.LoggerLevel) w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "ExecContext", name, 0, err)...).Log(ctx, w.opts.LoggerLevel)
} }
return nil, err return nil, err
} }
@ -189,7 +183,8 @@ func (w *wrapperStmt) ExecContext(ctx context.Context, args []driver.NamedValue)
te := td.Seconds() te := td.Seconds()
if err != nil { if err != nil {
w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelFailure)...).Inc() w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelFailure)...).Inc()
span.SetStatus(tracer.SpanStatusError, err.Error()) span.AddLabels("error", true)
span.AddLabels("err", err.Error())
} else { } else {
w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelSuccess)...).Inc() w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelSuccess)...).Inc()
} }
@ -198,7 +193,7 @@ func (w *wrapperStmt) ExecContext(ctx context.Context, args []driver.NamedValue)
w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te) w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te)
if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) { if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) {
w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "ExecContext", name, td, err)).Log(ctx, w.opts.LoggerLevel) w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "ExecContext", name, td, err)...).Log(ctx, w.opts.LoggerLevel)
} }
return res, err return res, err
@ -208,21 +203,21 @@ func (w *wrapperStmt) ExecContext(ctx context.Context, args []driver.NamedValue)
func (w *wrapperStmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) { func (w *wrapperStmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) {
var nctx context.Context var nctx context.Context
var span tracer.Span var span tracer.Span
if w.ctx != nil { if w.ctx != nil {
nctx, span = w.opts.Tracer.Start(w.ctx, "sdk.database", tracer.WithSpanKind(tracer.SpanKindClient)) nctx, span = w.opts.Tracer.Start(w.ctx, "QueryContext")
} else { } else {
nctx, span = w.opts.Tracer.Start(ctx, "sdk.database", tracer.WithSpanKind(tracer.SpanKindClient)) nctx, span = w.opts.Tracer.Start(ctx, "QueryContext")
} }
span.AddLabels("db.method", "QueryContext") span.AddLabels("method", "QueryContext")
name := getQueryName(ctx) name := getQueryName(ctx)
span.AddLabels("db.statement", name) if name != "" {
span.AddLabels("query", name)
} else {
name = labelUnknown
}
defer span.Finish() defer span.Finish()
if len(args) > 0 { if len(args) > 0 {
span.AddLabels("db.args", fmt.Sprintf("%v", namedValueToLabels(args))) span.AddLabels("args", fmt.Sprintf("%v", namedValueToLabels(args)))
}
if id, ok := ctx.Value(requestid.XRequestIDKey).(string); ok {
span.AddLabels("x-request-id", id)
} }
labels := []string{labelMethod, "QueryContext", labelQuery, name} labels := []string{labelMethod, "QueryContext", labelQuery, name}
if conn, ok := w.stmt.(driver.StmtQueryContext); ok { if conn, ok := w.stmt.(driver.StmtQueryContext); ok {
@ -232,7 +227,8 @@ func (w *wrapperStmt) QueryContext(ctx context.Context, args []driver.NamedValue
te := td.Seconds() te := td.Seconds()
if err != nil { if err != nil {
w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelFailure)...).Inc() w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelFailure)...).Inc()
span.SetStatus(tracer.SpanStatusError, err.Error()) span.AddLabels("error", true)
span.AddLabels("err", err.Error())
} else { } else {
w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelSuccess)...).Inc() w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelSuccess)...).Inc()
} }
@ -241,7 +237,7 @@ func (w *wrapperStmt) QueryContext(ctx context.Context, args []driver.NamedValue
w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te) w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te)
if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) { if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) {
w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "QueryContext", name, td, err)).Log(ctx, w.opts.LoggerLevel) w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "QueryContext", name, td, err)...).Log(ctx, w.opts.LoggerLevel)
} }
return rows, err return rows, err
} }
@ -250,10 +246,11 @@ func (w *wrapperStmt) QueryContext(ctx context.Context, args []driver.NamedValue
if err != nil { if err != nil {
w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelFailure)...).Inc() w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelFailure)...).Inc()
span.SetStatus(tracer.SpanStatusError, err.Error()) span.AddLabels("error", true)
span.AddLabels("err", err.Error())
if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) { if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) {
w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "QueryContext", name, 0, err)).Log(ctx, w.opts.LoggerLevel) w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "QueryContext", name, 0, err)...).Log(ctx, w.opts.LoggerLevel)
} }
return nil, err return nil, err
} }
@ -263,7 +260,8 @@ func (w *wrapperStmt) QueryContext(ctx context.Context, args []driver.NamedValue
te := td.Seconds() te := td.Seconds()
if err != nil { if err != nil {
w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelFailure)...).Inc() w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelFailure)...).Inc()
span.SetStatus(tracer.SpanStatusError, err.Error()) span.AddLabels("error", true)
span.AddLabels("err", err.Error())
} else { } else {
w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelSuccess)...).Inc() w.opts.Meter.Counter(meterRequestTotal, append(labels, labelStatus, labelSuccess)...).Inc()
} }
@ -272,7 +270,7 @@ func (w *wrapperStmt) QueryContext(ctx context.Context, args []driver.NamedValue
w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te) w.opts.Meter.Histogram(meterRequestDurationSeconds, labels...).Update(te)
if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) { if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) {
w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "QueryContext", name, td, err)).Log(ctx, w.opts.LoggerLevel) w.opts.Logger.Fields(w.opts.LoggerObserver(ctx, "QueryContext", name, td, err)...).Log(ctx, w.opts.LoggerLevel)
} }
return rows, err return rows, err

10
tx.go
View File

@ -26,13 +26,14 @@ func (w *wrapperTx) Commit() error {
if w.span != nil { if w.span != nil {
if err != nil { if err != nil {
w.span.SetStatus(tracer.SpanStatusError, err.Error()) w.span.AddLabels("error", true)
w.span.AddLabels("err", err.Error())
} }
w.span.Finish() w.span.Finish()
} }
if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) { if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) {
w.opts.Logger.Fields(w.opts.LoggerObserver(w.ctx, "Commit", getCallerName(), td, err)).Log(w.ctx, w.opts.LoggerLevel) w.opts.Logger.Fields(w.opts.LoggerObserver(w.ctx, "Commit", labelUnknown, td, err)...).Log(w.ctx, w.opts.LoggerLevel)
} }
w.ctx = nil w.ctx = nil
@ -48,13 +49,14 @@ func (w *wrapperTx) Rollback() error {
if w.span != nil { if w.span != nil {
if err != nil { if err != nil {
w.span.SetStatus(tracer.SpanStatusError, err.Error()) w.span.AddLabels("error", true)
w.span.AddLabels("err", err.Error())
} }
w.span.Finish() w.span.Finish()
} }
if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) { if w.opts.LoggerEnabled && w.opts.Logger.V(w.opts.LoggerLevel) {
w.opts.Logger.Fields(w.opts.LoggerObserver(w.ctx, "Rollback", getCallerName(), td, err)).Log(w.ctx, w.opts.LoggerLevel) w.opts.Logger.Fields(w.opts.LoggerObserver(w.ctx, "Rollback", labelUnknown, td, err)...).Log(w.ctx, w.opts.LoggerLevel)
} }
w.ctx = nil w.ctx = nil

112
wrap.go
View File

@ -11,6 +11,118 @@ func wrapDriver(d driver.Driver, opts Options) driver.Driver {
return struct{ driver.Driver }{&wrapperDriver{driver: d, opts: opts}} return struct{ driver.Driver }{&wrapperDriver{driver: d, opts: opts}}
} }
/*
func wrapStmt(stmt driver.Stmt, query string, opts Options) driver.Stmt {
var (
_, hasExeCtx = stmt.(driver.StmtExecContext)
_, hasQryCtx = stmt.(driver.StmtQueryContext)
wc, hasColConv = stmt.(driver.ColumnConverter) //nolint:staticcheck
wn, hasNamValChk = stmt.(driver.NamedValueChecker)
)
ws := &wrapperStmt{stmt: stmt, query: query, opts: opts}
switch {
case !hasExeCtx && !hasQryCtx && !hasColConv && !hasNamValChk:
return struct {
driver.Stmt
}{ws}
case !hasExeCtx && hasQryCtx && !hasColConv && !hasNamValChk:
return struct {
driver.Stmt
driver.StmtQueryContext
}{ws, ws}
case hasExeCtx && !hasQryCtx && !hasColConv && !hasNamValChk:
return struct {
driver.Stmt
driver.StmtExecContext
}{ws, ws}
case hasExeCtx && hasQryCtx && !hasColConv && !hasNamValChk:
return struct {
driver.Stmt
driver.StmtExecContext
driver.StmtQueryContext
}{ws, ws, ws}
case !hasExeCtx && !hasQryCtx && hasColConv && !hasNamValChk:
return struct {
driver.Stmt
driver.ColumnConverter
}{ws, wc}
case !hasExeCtx && hasQryCtx && hasColConv && !hasNamValChk:
return struct {
driver.Stmt
driver.StmtQueryContext
driver.ColumnConverter
}{ws, ws, wc}
case hasExeCtx && !hasQryCtx && hasColConv && !hasNamValChk:
return struct {
driver.Stmt
driver.StmtExecContext
driver.ColumnConverter
}{ws, ws, wc}
case hasExeCtx && hasQryCtx && hasColConv && !hasNamValChk:
return struct {
driver.Stmt
driver.StmtExecContext
driver.StmtQueryContext
driver.ColumnConverter
}{ws, ws, ws, wc}
case !hasExeCtx && !hasQryCtx && !hasColConv && hasNamValChk:
return struct {
driver.Stmt
driver.NamedValueChecker
}{ws, wn}
case !hasExeCtx && hasQryCtx && !hasColConv && hasNamValChk:
return struct {
driver.Stmt
driver.StmtQueryContext
driver.NamedValueChecker
}{ws, ws, wn}
case hasExeCtx && !hasQryCtx && !hasColConv && hasNamValChk:
return struct {
driver.Stmt
driver.StmtExecContext
driver.NamedValueChecker
}{ws, ws, wn}
case hasExeCtx && hasQryCtx && !hasColConv && hasNamValChk:
return struct {
driver.Stmt
driver.StmtExecContext
driver.StmtQueryContext
driver.NamedValueChecker
}{ws, ws, ws, wn}
case !hasExeCtx && !hasQryCtx && hasColConv && hasNamValChk:
return struct {
driver.Stmt
driver.ColumnConverter
driver.NamedValueChecker
}{ws, wc, wn}
case !hasExeCtx && hasQryCtx && hasColConv && hasNamValChk:
return struct {
driver.Stmt
driver.StmtQueryContext
driver.ColumnConverter
driver.NamedValueChecker
}{ws, ws, wc, wn}
case hasExeCtx && !hasQryCtx && hasColConv && hasNamValChk:
return struct {
driver.Stmt
driver.StmtExecContext
driver.ColumnConverter
driver.NamedValueChecker
}{ws, ws, wc, wn}
case hasExeCtx && hasQryCtx && hasColConv && hasNamValChk:
return struct {
driver.Stmt
driver.StmtExecContext
driver.StmtQueryContext
driver.ColumnConverter
driver.NamedValueChecker
}{ws, ws, ws, wc, wn}
}
panic("unreachable")
}
*/
// WrapConn allows an existing driver.Conn to be wrapped. // WrapConn allows an existing driver.Conn to be wrapped.
func WrapConn(c driver.Conn, opts ...Option) driver.Conn { func WrapConn(c driver.Conn, opts ...Option) driver.Conn {
return wrapConn(c, NewOptions(opts...)) return wrapConn(c, NewOptions(opts...))

File diff suppressed because it is too large Load Diff