package logmower import ( "context" "fmt" "time" 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 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: PrometheusPrefix, Subsystem: "database", 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: 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(time.Duration(ev.DurationNanos).Seconds()) }, 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(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) 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 }, }) }