Monitor GORM performance with OpenTelemetry

GORM is an ORM library for dealing with relational databases. It is developed on the top of database/sql package.

This article will teach you how to monitor GORM performance using OpenTelemetry observability framework.

What is OpenTelemetry?

OpenTelemetryopen in new window is a vendor-neutral standard that allows you to collect and export tracesopen in new window, logsopen in new window, and metricsopen in new window.

OpenTelemetry is a community-driven open source project that offers several components:

OpenTelemetry API and SDK are available for most programming languages and allows to send telemetry data to any tracing toolopen in new window of your choice.

Installation

To install GORM OpenTelemetry instrumentation:

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 context:

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

What is Uptrace?

Uptrace is an open source and blazingly fast distributed tracing tool powered by OpenTelemetry and ClickHouse. It allows you to identify and fix bugs in production faster knowing what conditions lead to which errors.

You can get startedopen in new window with Uptrace by downloading a DEB/RPM package or a pre-compiled Go binary.

What's next?

Next, instrument more operations, for example, database queries, errors, and logs. You can also learn about OpenTelemetry Go Tracing API to create your own instrumentations.

Popular instrumentations:

See also:

Last Updated: