Instrumenting GORM with OpenTelemetry

Introduction

otelgormopen in new window is an instrumentation for GORM 2 (v1.2+) that records database queries and reports sql.DBStats metrics. To instrument GORM 1, use otelsql.

Installation

To install otelgorm:

go get github.com/uptrace/opentelemetry-go-extra/otelgorm

Usage

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 contextopen in new window:

var num int
if err := db.WithContext(ctx).Raw("SELECT 42").Scan(&num).Error; err != nil {
	panic(err)
}

See exampleopen in new window for details.

Options

You can customize the plugin using configuration optionsopen in new window:

For example:

otelPlugin := otelgorm.NewPlugin(otelgorm.WithDBName("mydb"))

if err := db.Use(otelPlugin); err != nil {
	panic(err)
}

What is next?

Next, instrumentopen in new window more operations (for example, database queries or error logs) or learn about OpenTelemetry API to create your own instrumentations.