Module: RailsNamedCache::Logging

Defined in:
lib/rails_named_cache/logging.rb

Overview

Logs cache hits and misses at debug level.

It subscribes to the cache_read.active_support notification ActiveSupport already emits, so no store is wrapped and no cache API is added:

Cache hit: users/1
Cache miss: pricing:eur

Every read is logged, named or not — the notification is global. On Rails 7.2 and up the key is the normalized one, so a store's namespace: shows up as its prefix; earlier versions instrument the name the caller passed.

Constant Summary collapse

EVENT =

The only notification carrying :hit.

"cache_read.active_support"

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.subscriberObject? (readonly)

Returns the notification subscriber, or nil when not subscribed.

Returns:

  • (Object, nil)

    the notification subscriber, or nil when not subscribed



23
24
25
# File 'lib/rails_named_cache/logging.rb', line 23

def subscriber
  @subscriber
end

Class Method Details

.loggerLogger?

Returns the configured logger, or Rails.logger.

Returns:

  • (Logger, nil)

    the configured logger, or Rails.logger



56
57
58
# File 'lib/rails_named_cache/logging.rb', line 56

def logger
  @logger || (::Rails.logger if defined?(::Rails))
end

.subscribe(logger = nil) ⇒ Object?

Starts logging. Idempotent.

Parameters:

  • logger (Logger, nil, false) (defaults to: nil)

    nil resolves Rails.logger per event, false disables logging entirely

Returns:

  • (Object, nil)

    the subscriber, or nil when disabled or already subscribed



30
31
32
33
34
35
36
37
# File 'lib/rails_named_cache/logging.rb', line 30

def subscribe(logger = nil)
  return if logger == false || subscribed?

  @logger = logger
  @subscriber = ActiveSupport::Notifications.subscribe(EVENT) do |_name, _start, _finish, _id, payload|
    log(payload)
  end
end

.subscribed?Boolean

Returns:

  • (Boolean)


51
52
53
# File 'lib/rails_named_cache/logging.rb', line 51

def subscribed?
  !@subscriber.nil?
end

.unsubscribevoid

This method returns an undefined value.

Stops logging. Intended for tests and reboots.



42
43
44
45
46
47
48
# File 'lib/rails_named_cache/logging.rb', line 42

def unsubscribe
  return unless @subscriber

  ActiveSupport::Notifications.unsubscribe(@subscriber)
  @subscriber = nil
  @logger = nil
end