Monitor database/sql with OpenTelemetry

database/sql package provides a lightweight and idiomatic interface to row-oriented databases. It supports most popular relational DBMS via 3-rd party drivers.

This article will teach you how to monitor database/sql 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 database/sql OpenTelemetry instrumentation:

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

Usage

To instrument database/sql, you need to connect to a database using the API provided by otelsql:

sqlotelsql
sql.Open(driverName, dsn)otelsql.Open(driverName, dsn)
sql.OpenDB(connector)otelsql.OpenDB(connector)
import (
	"github.com/uptrace/opentelemetry-go-extra/otelsql"
	semconv "go.opentelemetry.io/otel/semconv/v1.4.0"
)

db, err := otelsql.Open("sqlite", "file::memory:?cache=shared",
	otelsql.WithAttributes(semconv.DBSystemSqlite),
	otelsql.WithDBName("mydb"))
if err != nil {
	panic(err)
}

// db is *sql.DB

And then use context-aware API to propagate the active span via context:

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

What is Uptrace?

Once your app is instrumented, you need a backend platform to store observability data collected by OpenTelemetry.

Uptrace is an open source APM for OpenTelemetry that helps developers pinpoint failures and find performance bottlenecks. Uptrace can process billions of spans on a single server and allows to monitor your software at 10x lower cost.

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: