GORM provides Prometheus plugin to collect DBStats or user-defined metrics

https://github.com/go-gorm/prometheus

Usage

  1. import (
  2. "gorm.io/gorm"
  3. "gorm.io/driver/sqlite"
  4. "gorm.io/plugin/prometheus"
  5. )
  6. db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{})
  7. db.Use(prometheus.New(prometheus.Config{
  8. DBName: "db1", // use `DBName` as metrics label
  9. RefreshInterval: 15, // Refresh metrics interval (default 15 seconds)
  10. PushAddr: "prometheus pusher address", // push metrics if `PushAddr` configured
  11. StartServer: true, // start http server to expose metrics
  12. HTTPServerPort: 8080, // configure http server port, default port 8080 (if you have configured multiple instances, only the first `HTTPServerPort` will be used to start server)
  13. MetricsCollector: []prometheus.MetricsCollector {
  14. &prometheus.MySQL{
  15. VariableNames: []string{"Threads_running"},
  16. },
  17. }, // user defined metrics
  18. }))

User-Defined Metrics

You can define your metrics and collect them with GORM Prometheus plugin, which needs to implements MetricsCollector interface

  1. type MetricsCollector interface {
  2. Metrics(*Prometheus) []prometheus.Collector
  3. }

MySQL

GORM provides an example for how to collect MySQL Status as metrics, check it out prometheus.MySQL

  1. &prometheus.MySQL{
  2. Prefix: "gorm_status_",
  3. // Metrics name prefix, default is `gorm_status_`
  4. // For example, Threads_running's metric name is `gorm_status_Threads_running`
  5. Interval: 100,
  6. // Fetch interval, default use Prometheus's RefreshInterval
  7. VariableNames: []string{"Threads_running"},
  8. // Select variables from SHOW STATUS, if not set, uses all status variables
  9. }