Golang ORM Performance and Errors Monitoring

What is OpenTelemetry?

Bun relies on OpenTelemetry to monitor database performance and errors using distributed tracingMonitoring performance and errors - 图1open in new window and metricsMonitoring performance and errors - 图2open in new window.

OpenTelemetryMonitoring performance and errors - 图3open in new window 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 bunotelMonitoring performance and errors - 图4open in new window that is distributed as a separate module:

  1. go get github.com/uptrace/bun/extra/bunotel

To instrument Bun database, you need to add the hook provided by bunotel:

  1. import "github.com/uptrace/bun/extra/bunotel"
  2. db := bun.NewDB(sqldb, dialect)
  3. db.AddQueryHook(bunotel.NewQueryHook(bunotel.WithDBName("mydb")))

To make tracing work, you must use the active span contextMonitoring performance and errors - 图5open in new window when executing queries, for example:

  1. ctx := req.Context()
  2. err := db.NewSelect().Scan(ctx)

Uptrace

UptraceMonitoring performance and errors - 图6open in new window is an open source DataDog alternativeMonitoring performance and errors - 图7open in new window 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 install UptraceMonitoring performance and errors - 图8open in new window by downloading a DEB/RPM package or a pre-compiled binary.

As expected, otelbun creates spansMonitoring performance and errors - 图9open in new window for processed queries and records any errors as they occur. Here is how the collected information is displayed at UptraceMonitoring performance and errors - 图10open in new window:

Bun trace

You can find a runnable example at GitHubMonitoring performance and errors - 图12open in new window.

Prometheus

You can send OpenTelemetry metrics to Prometheus using OpenTelemetry Prometheus exporterMonitoring performance and errors - 图13open in new window. Alternatively, you can also use j2gg0s/otsqlMonitoring performance and errors - 图14open in new window that directly works with Prometheus.

See also