package maintnotifications
import (
"context"
"fmt"
"time"
"github.com/redis/go-redis/v9/internal"
"github.com/redis/go-redis/v9/internal/maintnotifications/logs"
"github.com/redis/go-redis/v9/internal/pool"
"github.com/redis/go-redis/v9/push"
)
type contextKey string
const (
startTimeKey contextKey = "maint_notif_start_time"
)
type MetricsHook struct {
NotificationCounts map [string ]int64
ProcessingTimes map [string ]time .Duration
ErrorCounts map [string ]int64
HandoffCounts int64
HandoffSuccesses int64
HandoffFailures int64
}
func NewMetricsHook () *MetricsHook {
return &MetricsHook {
NotificationCounts : make (map [string ]int64 ),
ProcessingTimes : make (map [string ]time .Duration ),
ErrorCounts : make (map [string ]int64 ),
}
}
func (mh *MetricsHook ) PreHook (ctx context .Context , notificationCtx push .NotificationHandlerContext , notificationType string , notification []interface {}) ([]interface {}, bool ) {
mh .NotificationCounts [notificationType ]++
if conn , ok := notificationCtx .Conn .(*pool .Conn ); ok {
internal .Logger .Printf (ctx , "%s" , logs .MetricsHookProcessingNotification (notificationType , conn .GetID ()))
}
startTime := time .Now ()
_ = context .WithValue (ctx , startTimeKey , startTime )
return notification , true
}
func (mh *MetricsHook ) PostHook (ctx context .Context , notificationCtx push .NotificationHandlerContext , notificationType string , notification []interface {}, result error ) {
if startTime , ok := ctx .Value (startTimeKey ).(time .Time ); ok {
duration := time .Since (startTime )
mh .ProcessingTimes [notificationType ] = duration
}
if result != nil {
mh .ErrorCounts [notificationType ]++
if conn , ok := notificationCtx .Conn .(*pool .Conn ); ok {
internal .Logger .Printf (ctx , "%s" , logs .MetricsHookRecordedError (notificationType , conn .GetID (), result ))
}
}
}
func (mh *MetricsHook ) GetMetrics () map [string ]interface {} {
return map [string ]interface {}{
"notification_counts" : mh .NotificationCounts ,
"processing_times" : mh .ProcessingTimes ,
"error_counts" : mh .ErrorCounts ,
}
}
func ExampleCircuitBreakerMonitor (poolHook *PoolHook ) {
stats := poolHook .GetCircuitBreakerStats ()
for _ , stat := range stats {
fmt .Printf ("Circuit Breaker for %s:\n" , stat .Endpoint )
fmt .Printf (" State: %s\n" , stat .State )
fmt .Printf (" Failures: %d\n" , stat .Failures )
fmt .Printf (" Last Failure: %v\n" , stat .LastFailureTime )
fmt .Printf (" Last Success: %v\n" , stat .LastSuccessTime )
if stat .State .String () == "open" {
fmt .Printf (" ⚠️ ALERT: Circuit breaker is OPEN for %s\n" , stat .Endpoint )
}
}
}
The pages are generated with Golds v0.8.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .