Bluemage/go/pkg/log/sql.go

49 lines
1.1 KiB
Go
Raw Normal View History

2024-08-08 13:41:18 +07:00
package log
import (
"context"
"log/slog"
"strings"
sqldblogger "github.com/simukti/sqldb-logger"
)
var _ sqldblogger.Logger = (*SQLLogger)(nil)
type SQLLogger struct{}
var _ slog.LogValuer = (*QueryCollector)(nil)
type QueryCollector struct {
Statement string
Args any
}
func (qu *QueryCollector) LogValue() slog.Value {
return slog.GroupValue(
slog.String("statement", qu.Statement),
2024-08-08 13:41:18 +07:00
slog.Any("args", qu.Args),
)
}
type queryCollectorKey struct{}
func QueryCollectorFromContext(ctx context.Context) *QueryCollector {
coll, _ := ctx.Value(queryCollectorKey{}).(*QueryCollector)
return coll
}
func WithQueryCollector(ctx context.Context) (context.Context, *QueryCollector) {
coll := &QueryCollector{}
return context.WithValue(ctx, queryCollectorKey{}, coll), coll
}
func (SQLLogger) Log(ctx context.Context, level sqldblogger.Level, msg string, data map[string]interface{}) {
if qc := QueryCollectorFromContext(ctx); qc != nil {
qc.Statement = msg
qc.Args = data["args"]
return
}
2024-08-27 09:10:58 +07:00
slog.DebugContext(ctx, strings.ReplaceAll(msg, "\n", " "), "lvl", level.String(), "data", data)
2024-08-08 13:41:18 +07:00
}