SQL Instrumentation

Setup

To instrument your SQL usage, you'll need to import the OpenTelemetry official instrumentation packages:

go
import( "github.com/XSAM/otelsql" semconv "go.opentelemetry.io/otel/semconv/v1.4.0" )

Your DB connection must be opened using the otelsql package, it's also important to query the database using the QueryContext function to pass the current context, that way, the spans will be properly nested and structured. The example below shows how to instrument queries to a MySQL database in a web request context.

For more information about usage and SQL drivers support, take a look at the package repository.

go
func mysqlQuery(w http.ResponseWriter, r *http.Request) { ctx := r.Context() db, err := otelsql.Open( "mysql", "root:password@tcp(0.0.0.0:3306)/mydb", otelsql.WithAttributes(semconv.DBSystemMySQL), ) if err != nil { panic(err) } defer db.Close() rows, err := db.QueryContext(ctx, "select * from mysql.user") if err != nil { panic(err) } defer rows.Close() }