Class: ActiveReplicas::LogSubscriber

Inherits:
ActiveRecord::LogSubscriber
  • Object
show all
Defined in:
lib/active_replicas/log_subscriber.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.hijack_active_recordObject

Take over logging duties from ‘ActiveRecord::LogSubscriber`.



46
47
48
49
50
51
52
53
54
# File 'lib/active_replicas/log_subscriber.rb', line 46

def self.hijack_active_record
  self.attach_to :active_record

  subscriber = ActiveSupport::Notifications.notifier.listeners_for('sql.active_record').find do |subscriber|
    ActiveRecord::LogSubscriber === subscriber.instance_eval { @delegate }
  end

  ActiveSupport::Notifications.notifier.unsubscribe(subscriber) if subscriber
end

Instance Method Details

#loggerObject



41
42
43
# File 'lib/active_replicas/log_subscriber.rb', line 41

def logger
  ActiveRecord::Base.logger
end

#sql(event) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/active_replicas/log_subscriber.rb', line 5

def sql(event)
  self.class.runtime += event.duration
  return unless logger.debug?

  payload = event.payload

  return if IGNORE_PAYLOAD_NAMES.include?(payload[:name])

  pool  = nil
  name  = "#{payload[:name]} (#{event.duration.round(1)}ms)"
  sql   = payload[:sql]
  binds = nil

  proxy = ActiveRecord::Base.connection_handler.proxying_connection_pool
  connection_pool = proxy.pool_which_owns_connection payload[:connection_id]
  if connection_pool
    role =
      if proxy.primary_pool? connection_pool
        'primary'
      elsif proxy.replica_pool? connection_pool
        pool_name = proxy.replica_pools.key connection_pool
        "replica=#{pool_name}"
      else
        'unknown'
      end

    pool = "[#{role}] "
  end

  unless (payload[:binds] || []).empty?
    binds = ' ' + payload[:binds].map { |column, value| render_bind(column, value) }.inspect
  end

  debug "#{pool}#{name} #{sql}#{binds}"
end