### Install sqlstats Go Library Source: https://github.com/dlmiddlecote/sqlstats/blob/main/README.md Use 'go get' to install the sqlstats library. This command fetches and installs the specified package and its dependencies. ```bash go get github.com/dlmiddlecote/sqlstats ``` -------------------------------- ### Example Usage of sqlstats Source: https://github.com/dlmiddlecote/sqlstats/blob/main/README.md This example demonstrates how to integrate sqlstats into a Go application. It opens a database connection, creates a stats collector, registers it with Prometheus, and starts an HTTP server to expose metrics. ```go package main import ( "database/sql" "net/http" _ "github.com/lib/pq" "github.com/dlmiddlecote/sqlstats" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" ) func main() { if err := run(); err != nil { panic(err) } } func run() error { // Open connection to a DB (could also use the https://github.com/jmoiron/sqlx library) db, err := sql.Open("postgres", "postgres://postgres:postgres@localhost:5432/postgres") if err != nil { return err } // Create a new collector, the name will be used as a label on the metrics collector := sqlstats.NewStatsCollector("db_name", db) // Register it with Prometheus prometheus.MustRegister(collector) // Register the metrics handler http.Handle("/metrics", promhttp.Handler()) // Run the web server return http.ListenAndServe(":8080", nil) } ``` -------------------------------- ### Basic Usage: Collect and Export DB Stats with Prometheus Source: https://context7.com/dlmiddlecote/sqlstats/llms.txt Demonstrates how to open a database connection, create a sqlstats collector, register it with the default Prometheus registry, and expose metrics via an HTTP server. Ensure the database driver is imported. ```go package main import ( "database/sql" "log" "net/http" _ "github.com/lib/pq" "github.com/dlmiddlecote/sqlstats" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" ) func main() { // Open a PostgreSQL connection pool db, err := sql.Open("postgres", "postgres://user:pass@localhost:5432/mydb?sslmode=disable") if err != nil { log.Fatalf("failed to open db: %v", err) } defer db.Close() // Tune the pool (stats will reflect these limits) db.SetMaxOpenConns(25) db.SetMaxIdleConns(10) // Create a collector labeled "mydb" and register it with the default registry collector := sqlstats.NewStatsCollector("mydb", db) if err := prometheus.Register(collector); err != nil { log.Fatalf("failed to register collector: %v", err) } http.Handle("/metrics", promhttp.Handler()) log.Println("Serving metrics on :8080/metrics") log.Fatal(http.ListenAndServe(":8080", nil)) } // Example Prometheus output at /metrics: // go_sql_stats_connections_max_open{db_name="mydb"} 25 // go_sql_stats_connections_open{db_name="mydb"} 4 // go_sql_stats_connections_in_use{db_name="mydb"} 2 // go_sql_stats_connections_idle{db_name="mydb"} 2 // go_sql_stats_connections_waited_for{db_name="mydb"} 0 // go_sql_stats_connections_blocked_seconds{db_name="mydb"} 0 // go_sql_stats_connections_closed_max_idle{db_name="mydb"} 0 // go_sql_stats_connections_closed_max_lifetime{db_name="mydb"} 0 // go_sql_stats_connections_closed_max_idle_time{db_name="mydb"} 0 (Go 1.15+) ``` -------------------------------- ### Registering with a Custom Prometheus Registry Source: https://context7.com/dlmiddlecote/sqlstats/llms.txt Shows how to use a custom Prometheus registry instead of the default one, useful for more complex metric management or isolated testing. This involves creating a new registry and using `promhttp.HandlerFor`. ```go // Registering with a custom (non-default) Prometheus registry registry := prometheus.NewRegistry() db, _ := sql.Open("sqlite3", ":memory:") collector := sqlstats.NewStatsCollector("sqlite_pool", db) // Describe and Collect are wired up automatically via Register if err := registry.Register(collector); err != nil { log.Fatal(err) } // Expose on a custom mux using the custom registry mux := http.NewServeMux() mux.Handle("/metrics", promhttp.HandlerFor(registry, promhttp.HandlerOpts{})) log.Fatal(http.ListenAndServe(":9090", mux)) ``` -------------------------------- ### Manual Metric Collection for Testing Source: https://context7.com/dlmiddlecote/sqlstats/llms.txt Illustrates how to manually trigger the collection of metrics from a `StatsCollector` instance, typically used for testing or custom reporting scenarios outside of a standard HTTP scrape. The collected metrics are read from a channel. ```go // Manual collection (e.g., for testing or custom reporting) db, _ := sql.Open("sqlite3", ":memory:") collector := sqlstats.NewStatsCollector("test_db", db) ch := make(chan prometheus.Metric, 16) go func() { collector.Collect(ch) close(ch) }() for m := range ch { desc := m.Desc() log.Println("collected metric:", desc.String()) } ``` -------------------------------- ### Use SQLStats with sqlx Source: https://context7.com/dlmiddlecote/sqlstats/llms.txt The *sqlx.DB type implements the StatsGetter interface, allowing it to be passed directly to NewStatsCollector without needing an adapter. This enables monitoring of databases managed by sqlx. ```go import ( "log" "net/http" _ "github.com/lib/pq" "github.com/dlmiddlecote/sqlstats" "github.com/jmoiron/sqlx" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" ) func main() { db, err := sqlx.Connect("postgres", "postgres://user:pass@localhost:5432/mydb") if err != nil { log.Fatal(err) } // *sqlx.DB implements StatsGetter — no adapter needed prometheus.MustRegister(sqlstats.NewStatsCollector("pg_primary", db)) http.Handle("/metrics", promhttp.Handler()) log.Fatal(http.ListenAndServe(":8080", nil)) } ``` -------------------------------- ### StatsGetter Interface Definition Source: https://context7.com/dlmiddlecote/sqlstats/llms.txt Defines the StatsGetter interface, which is implemented by *sql.DB and *sqlx.DB to retrieve database statistics. ```go package main import ( "database/sql" ) // StatsGetter is an interface that gets sql.DBStats. // It's implemented by e.g. *sql.DB or *sqlx.DB. type StatsGetter interface { Stats() sql.DBStats } ``` -------------------------------- ### Monitor Multiple Databases with SQLStats Source: https://context7.com/dlmiddlecote/sqlstats/llms.txt Register multiple StatsCollector instances with unique dbName labels against the same Prometheus registry to monitor different databases. The db_name label differentiates the metric series. ```go package main import ( "database/sql" "log" "net/http" _ "github.com/mattn/go-sqlite3" "github.com/dlmiddlecote/sqlstats" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" ) func main() { primary, err := sql.Open("sqlite3", "primary.db") if err != nil { log.Fatal(err) } replica, err := sql.Open("sqlite3", "replica.db") if err != nil { log.Fatal(err) } // Each collector carries a distinct db_name label prometheus.MustRegister(sqlstats.NewStatsCollector("primary", primary)) prometheus.MustRegister(sqlstats.NewStatsCollector("replica", replica)) http.Handle("/metrics", promhttp.Handler()) log.Fatal(http.ListenAndServe(":8080", nil)) // Resulting metric series (example): // go_sql_stats_connections_open{db_name="primary"} 3 // go_sql_stats_connections_open{db_name="replica"} 1 } ``` -------------------------------- ### NewStatsCollector Source: https://context7.com/dlmiddlecote/sqlstats/llms.txt Creates a new Prometheus collector for a given database connection pool. The dbName is used as a label for the metrics. ```APIDOC ## NewStatsCollector(dbName string, sg StatsGetter) *StatsCollector ### Description `NewStatsCollector` creates a new Prometheus collector for the given database connection pool. The `dbName` string becomes the value of the `db_name` label on every metric, allowing multiple databases to be monitored simultaneously without label collisions. ### Parameters * `dbName` (string) - The name of the database to be used as a label for the metrics. * `sg` (StatsGetter) - An interface that provides `sql.DBStats`. ``` -------------------------------- ### StatsCollector.Describe Source: https://context7.com/dlmiddlecote/sqlstats/llms.txt Implements the prometheus.Collector interface to send metric descriptors to a channel. This is called automatically by the Prometheus registry. ```APIDOC ## StatsCollector.Describe(ch chan<- *prometheus.Desc) ### Description `Describe` implements the `prometheus.Collector` interface and sends the descriptors for all exported metrics into the provided channel. It is called automatically by the Prometheus registry during `Register`; you do not need to call it manually. ``` -------------------------------- ### StatsCollector.Collect Source: https://context7.com/dlmiddlecote/sqlstats/llms.txt Implements the prometheus.Collector interface to collect and emit current metric values. This is invoked automatically by the Prometheus HTTP handler. ```APIDOC ## StatsCollector.Collect(ch chan<- prometheus.Metric) ### Description `Collect` implements the `prometheus.Collector` interface. On each scrape it calls `Stats()` on the underlying `StatsGetter` and emits current gauge and counter values. It is invoked automatically by the Prometheus HTTP handler on every `/metrics` request. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.