logmower-shipper/pkg/mongo/metrics.go
2022-11-09 18:07:28 +02:00

61 lines
2.3 KiB
Go

package mongo
import (
"context"
"log"
"time"
"git.k-space.ee/k-space/logmower-shipper/pkg/globals"
prom "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
mongoEvent "go.mongodb.org/mongo-driver/event"
mongoOpt "go.mongodb.org/mongo-driver/mongo/options"
)
const promSubsystem = "database"
var (
promDbHeartbeat = promauto.NewHistogramVec(prom.HistogramOpts{
Namespace: globals.PrometheusPrefix, Subsystem: promSubsystem,
Name: "heartbeat_time",
Help: "Time in seconds for succeeded heartbeat, or 0 on failure",
Buckets: []float64{0.1, 0.2, 0.5, 1, 5, 10, 50},
}, []string{"connection_id"})
promDbCmd = promauto.NewHistogramVec(prom.HistogramOpts{
Namespace: globals.PrometheusPrefix, Subsystem: promSubsystem,
Name: "operation_latency", // "command_time",
Help: "Time in seconds of commands",
Buckets: []float64{0.1, 0.2, 0.5, 1, 5, 10, 50},
}, []string{"connection_id", "command_name"})
promDbCmdErr = promauto.NewCounterVec(prom.CounterOpts{
Namespace: globals.PrometheusPrefix, Subsystem: promSubsystem,
Name: "errors",
Help: "Failed commands (also reflected elsewhere)",
}, []string{"connection_id", "command_name"})
)
func monitoredClientOptions() *mongoOpt.ClientOptions {
return mongoOpt.Client().
SetServerMonitor(&mongoEvent.ServerMonitor{
ServerHeartbeatSucceeded: func(ev *mongoEvent.ServerHeartbeatSucceededEvent) {
promDbHeartbeat.WithLabelValues(ev.ConnectionID).Observe(time.Duration(ev.DurationNanos).Seconds())
},
ServerHeartbeatFailed: func(ev *mongoEvent.ServerHeartbeatFailedEvent) {
promDbHeartbeat.WithLabelValues(ev.ConnectionID).Observe(0)
log.Printf("database heartbeat failed on connection %q: %e", ev.ConnectionID, ev.Failure)
},
}).
SetMonitor(&mongoEvent.CommandMonitor{
Succeeded: func(_ context.Context, ev *mongoEvent.CommandSucceededEvent) {
promDbCmd.WithLabelValues(ev.ConnectionID, ev.CommandName).Observe(time.Duration(ev.DurationNanos).Seconds())
},
Failed: func(_ context.Context, ev *mongoEvent.CommandFailedEvent) {
promDbCmd.WithLabelValues(ev.ConnectionID, ev.CommandName).Observe(time.Duration(ev.DurationNanos).Seconds())
promDbCmdErr.WithLabelValues(ev.ConnectionID, ev.CommandName).Add(1)
},
})
}