OpenTelemetry GORM instrumentation
records database queries and reports DBStats
metrics.
go get github.com/uptrace/opentelemetry-go-extra/otelgorm
To instrument GORM, you need to install the plugin provided by otelgorm:
import (
"github.com/uptrace/opentelemetry-go-extra/otelgorm"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
db, err := gorm.Open(sqlite.Open("file::memory:?cache=shared"), &gorm.Config{})
if err != nil {
panic(err)
}
if err := db.Use(otelgorm.NewPlugin()); err != nil {
panic(err)
}
And then use db.WithContext(ctx)
to propagate the active span via
context:
var num int
if err := db.WithContext(ctx).Raw("SELECT 42").Scan(&num).Error; err != nil {
panic(err)
}
See example for details.
You can customize the plugin using configuration options:
- WithAttributes configures attributes that are used to create a span.
- WithDBName
configures a
db.name
attribute.
For example:
otelPlugin := otelgorm.NewPlugin(otelgorm.WithDBName("mydb"))
if err := db.Use(otelPlugin); err != nil {
panic(err)
}