You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 line
2.1 KiB

  1. package maintnotifications
  2. import (
  3. "context"
  4. "slices"
  5. "github.com/redis/go-redis/v9/internal"
  6. "github.com/redis/go-redis/v9/internal/maintnotifications/logs"
  7. "github.com/redis/go-redis/v9/internal/pool"
  8. "github.com/redis/go-redis/v9/push"
  9. )
  10. // LoggingHook is an example hook implementation that logs all notifications.
  11. type LoggingHook struct {
  12. LogLevel int // 0=Error, 1=Warn, 2=Info, 3=Debug
  13. }
  14. // PreHook logs the notification before processing and allows modification.
  15. func (lh *LoggingHook) PreHook(ctx context.Context, notificationCtx push.NotificationHandlerContext, notificationType string, notification []interface{}) ([]interface{}, bool) {
  16. if lh.LogLevel >= 2 { // Info level
  17. // Log the notification type and content
  18. connID := uint64(0)
  19. if conn, ok := notificationCtx.Conn.(*pool.Conn); ok {
  20. connID = conn.GetID()
  21. }
  22. seqID := int64(0)
  23. if slices.Contains(maintenanceNotificationTypes, notificationType) {
  24. // seqID is the second element in the notification array
  25. if len(notification) > 1 {
  26. if parsedSeqID, ok := notification[1].(int64); !ok {
  27. seqID = 0
  28. } else {
  29. seqID = parsedSeqID
  30. }
  31. }
  32. }
  33. internal.Logger.Printf(ctx, logs.ProcessingNotification(connID, seqID, notificationType, notification))
  34. }
  35. return notification, true // Continue processing with unmodified notification
  36. }
  37. // PostHook logs the result after processing.
  38. func (lh *LoggingHook) PostHook(ctx context.Context, notificationCtx push.NotificationHandlerContext, notificationType string, notification []interface{}, result error) {
  39. connID := uint64(0)
  40. if conn, ok := notificationCtx.Conn.(*pool.Conn); ok {
  41. connID = conn.GetID()
  42. }
  43. if result != nil && lh.LogLevel >= 1 { // Warning level
  44. internal.Logger.Printf(ctx, logs.ProcessingNotificationFailed(connID, notificationType, result, notification))
  45. } else if lh.LogLevel >= 3 { // Debug level
  46. internal.Logger.Printf(ctx, logs.ProcessingNotificationSucceeded(connID, notificationType))
  47. }
  48. }
  49. // NewLoggingHook creates a new logging hook with the specified log level.
  50. // Log levels: 0=Error, 1=Warn, 2=Info, 3=Debug
  51. func NewLoggingHook(logLevel int) *LoggingHook {
  52. return &LoggingHook{LogLevel: logLevel}
  53. }