Skip to content

A Go library for collecting sql.DBStats taken from *sql.DB connection

License

Notifications You must be signed in to change notification settings

krpn/go-sql-db-stats

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

go-sql-db-stats

GoDoc Go Report License

  • A Go library for collecting sql.DBStats taken from *sql.DB connection
  • Can collect metrics in Prometheus format
  • Can repeatedly pass sql.DBStats in your own Collector (see docs)

Exposed Prometheus Metrics

Name Description Labels
sql_db_stats sql.DBStats metrics and values db_name metric

Installation

go get github.com/krpn/go-sql-db-stats

Example Usage

package main

import (
	"database/sql"
	"fmt"
	"github.com/krpn/go-sql-db-stats"
	_ "github.com/lib/pq"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"net/http"
	"time"
)

// docker run --name some-postgres -p 5432:5432 -e POSTGRES_PASSWORD=mysecretpassword -d postgres:11.2
var exampleConnString = fmt.Sprintf(
	"host=%v port=%v user=%v password=%v dbname=%v sslmode=disable binary_parameters=yes",
	"localhost", 5432, "postgres", "mysecretpassword", "postgres",
)

func main() {
	db, err := sql.Open("postgres", exampleConnString)
	if err != nil {
		panic(err)
	}
	defer func() {
		panic(db.Close())
	}()
	db.SetMaxOpenConns(10)
	db.SetMaxIdleConns(10)

	_ = sqldbstats.StartCollectPrometheusMetrics(db, 30*time.Second, "main_db")
	// If you want to stop collecting at any moment (for example: after close db), you may use this code:
	// collector := sqldbstats.StartCollectPrometheusMetrics(db, 30*time.Second, "main_db")
	// defer collector.Stop()

	http.HandleFunc("/handler", someHandler(db))
	http.Handle("/metrics", promhttp.Handler())
	panic(http.ListenAndServe(":8080", nil))
}

func someHandler(db *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var t time.Time
		err := db.QueryRow("select now();").Scan(&t)
		if err != nil {
			_, _ = fmt.Fprintf(w, "Result: %v", err)
			return
		}
		_, _ = fmt.Fprintf(w, "Result: %v", t)
	}
}

About

A Go library for collecting sql.DBStats taken from *sql.DB connection

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages