package logmower import ( "context" "fmt" 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" "go.uber.org/zap" ) var ( promDbHeartbeat = promauto.NewHistogramVec(prom.HistogramOpts{ Namespace: PrometheusPrefix, Subsystem: "database", Name: "heartbeat_time", Help: "Time in ns for succeeded heartbeat, or 0 on failure", Buckets: []float64{1}, }, []string{"connection_id"}) promDbCmd = promauto.NewHistogramVec(prom.HistogramOpts{ Namespace: PrometheusPrefix, Subsystem: "database", Name: "operation_latency", // "command_time", Help: "Time in ns 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: PrometheusPrefix, Subsystem: "database", Name: "errors", Help: "Failed commands (also reflected elsewhere)", }, []string{"connection_id", "command_name"}) ) func mongoMonitoredClientOptions(l *zap.Logger) *mongoOpt.ClientOptions { return mongoOpt.Client(). SetServerMonitor(&mongoEvent.ServerMonitor{ ServerHeartbeatSucceeded: func(ev *mongoEvent.ServerHeartbeatSucceededEvent) { promDbHeartbeat.WithLabelValues(ev.ConnectionID).Observe(float64(ev.DurationNanos)) }, ServerHeartbeatFailed: func(ev *mongoEvent.ServerHeartbeatFailedEvent) { promDbHeartbeat.WithLabelValues(ev.ConnectionID).Observe(0) l.Error("database heartbeat", zap.Error(ev.Failure), zap.String("connection_id", ev.ConnectionID)) }, }). SetMonitor(&mongoEvent.CommandMonitor{ Succeeded: func(_ context.Context, ev *mongoEvent.CommandSucceededEvent) { promDbCmd.WithLabelValues(ev.ConnectionID, ev.CommandName).Observe(float64(ev.DurationNanos)) }, Failed: func(_ context.Context, ev *mongoEvent.CommandFailedEvent) { promDbCmd.WithLabelValues(ev.ConnectionID, ev.CommandName).Observe(float64(ev.DurationNanos)) promDbCmdErr.WithLabelValues(ev.ConnectionID, ev.CommandName).Add(1) l.Error("database command", zap.Error(fmt.Errorf("%s", ev.Failure)), zap.String("connection_id", ev.ConnectionID), zap.String("command_name", ev.CommandName)) // TODO: https://github.com/mongodb/mongo-go-driver/pull/1105 }, }) }