Bun Performance Monitoring
What is OpenTelemetry?
Bun relies on OpenTelemetry to monitor database performance and errors using OpenTelemetry tracing and OpenTelemetry metrics.
OpenTelemetry is a vendor-neutral API for distributed traces and metrics. It specifies how to collect and send telemetry data to backend platforms. It means that you can instrument your application once and then add or change vendors (backends) as required.
OpenTelemetry instrumentaton
Bun comes with an OpenTelemetry instrumentation called bunotel that is distributed as a separate module:
go get github.com/uptrace/bun/extra/bunotel
To instrument Bun database, you need to add the hook provided by bunotel:
import "github.com/uptrace/bun/extra/bunotel"
db := bun.NewDB(sqldb, dialect)
db.AddQueryHook(bunotel.NewQueryHook(bunotel.WithDBName("mydb")))
To make tracing work, you must use an active span context when executing queries, for example:
ctx := req.Context()
err := db.NewSelect().Scan(ctx)
Uptrace
Uptrace is an open-source APM and a popular DataDog competitor that supports distributed tracing, metrics, and logs. You can use it to monitor applications and set up automatic alerts to receive notifications via email, Slack, Telegram, and more.
You can install Uptrace by downloading a DEB/RPM package or a pre-compiled binary.
As expected, otelbun creates spans for processed queries and records any errors as they occur. Here is how the collected information is displayed at Uptrace:
You can find a runnable example at GitHub.
Prometheus
You can also send OpenTelemetry metrics to Prometheus using OpenTelemetry Prometheus exporter.
What's next?
Next, start using Uptrace by following the Getting started guide.
You can also check the following guides to monitor features specific to your RDBMS: