“...I've been working since 2008 with Ruby / Ruby on Rails, love a bit of Elixir / Phoenix and learning Rust. I also poke through other people's code and make PRs for OpenSource Ruby projects that sometimes make it. Currently working for InPay...”

Rob Lacey (contact@robl.me)
Senior Software Engineer, Brighton, UK

Hooking into ActiveRecord logging

Quick and dirty hook to log long SQL queries and their caller.

ActiveSupport::Notifications.subscribe 'sql.active_record' do |name, start, finish, id, payload|
  time = (finish - start) * 1000
  if payload[:sql] && time > 500
    time = (time * 1000).to_i / 1000.0
    c = caller.select { |l| l =~ /something_(core|music|artists)/ }[0]
    logger = Logger.new(Rails.root.join('log', 'active_record_slow_queries.log'))
    logger.info("(#{time}s) #{payload[:sql]} - #{c}")
  end
end