|
| 1 | +//go:build go1.17 |
| 2 | +// +build go1.17 |
| 3 | + |
| 4 | +// A minimal example of how to include Prometheus instrumentation for database stats. |
| 5 | +package main |
| 6 | + |
| 7 | +import ( |
| 8 | + "database/sql" |
| 9 | + "flag" |
| 10 | + "fmt" |
| 11 | + "log" |
| 12 | + "net/http" |
| 13 | + "time" |
| 14 | + |
| 15 | + _ "github.com/mattn/go-sqlite3" |
| 16 | + "github.com/prometheus/client_golang/prometheus" |
| 17 | + "github.com/prometheus/client_golang/prometheus/collectors" |
| 18 | + "github.com/prometheus/client_golang/prometheus/promhttp" |
| 19 | +) |
| 20 | + |
| 21 | +var addr = flag.String("listen-address", ":8080", "The address to listen on for HTTP requests.") |
| 22 | + |
| 23 | +func main() { |
| 24 | + flag.Parse() |
| 25 | + |
| 26 | + // Set up an in-memory SQLite DB. |
| 27 | + db, err := sql.Open("sqlite3", ":memory:") // In-memory SQLite database |
| 28 | + if err != nil { |
| 29 | + log.Fatalf("Failed to connect to in-memory database: %v", err) |
| 30 | + } |
| 31 | + defer db.Close() |
| 32 | + |
| 33 | + // Set connection pool limits to simulate more activity. |
| 34 | + db.SetMaxOpenConns(10) |
| 35 | + db.SetMaxIdleConns(5) |
| 36 | + db.SetConnMaxIdleTime(5 * time.Minute) |
| 37 | + db.SetConnMaxLifetime(30 * time.Minute) |
| 38 | + |
| 39 | + // Create a new Prometheus registry. |
| 40 | + reg := prometheus.NewRegistry() |
| 41 | + |
| 42 | + // Create and register the DB stats collector. |
| 43 | + dbStatsCollector := collectors.NewDBStatsCollector(db, "sqlite_in_memory") |
| 44 | + reg.MustRegister(dbStatsCollector) |
| 45 | + |
| 46 | + // Expose the registered metrics via HTTP. |
| 47 | + http.Handle("/metrics", promhttp.HandlerFor( |
| 48 | + reg, |
| 49 | + promhttp.HandlerOpts{}, |
| 50 | + )) |
| 51 | + |
| 52 | + fmt.Println("Server is running, metrics are available at /metrics") |
| 53 | + log.Fatal(http.ListenAndServe(*addr, nil)) |
| 54 | +} |
0 commit comments