The following monkey patch gives a bit more information in the ActiveRecord SQL logs. Instead of just saying “User Load” it also says the file and line number in your code that asked AR to perform the operation. That way you can have a hope of tracking it down and optimizing it away if at all possible.
User Load (0.2ms) views/main_page.rb:107:in `filters_box' SELECT * FROM `users`
Code after the jump. I guess you put it in environment.rb with all the other monkeys.
module ActiveRecord
module ConnectionAdapters
class AbstractAdapter
def log_info(sql, name, ms)
if @logger && @logger.debug?
c = caller.detect{|line| line !~ /(activerecord|active_support|__DELEGATION__)/i}
c.gsub!("#{File.expand_path(File.dirname(RAILS_ROOT))}/", '') if defined?(RAILS_ROOT)
name = '%s (%.1fms) %s' % [name || 'SQL', ms, c]
@logger.debug(format_log_entry(name, sql.squeeze(' ')))
end
end
end
end
end
Gisting: http://gist.github.com/116987
Thanks for this, I’m kinda surprised it’s not in rails. I’m gonna play around with it a bit to see if there’s a compelling case for sending it upstream.
May 24, 2009 at 6:33 am
Jack – I see you’re playing around with the matching expression. Good call on adding “vendor” — though I’m not sure we wouldn’t want to see that it’s, say, the “acts_as_asinine” plugin that’s calling save 18 times in a row… And I’d leave “lib” out since “lib” often contains application code. I smell a configuration option…
Here’s the gist URL in clickable form:
[http://gist.github.com/116987](http://gist.github.com/116987)
May 24, 2009 at 4:18 pm
As another data point, Rack::Bug has a query report. Its filter is the opposite of the above: it chooses only files that are inside RAILS_ROOT (and not in “vendor”).
Oh, and (Rack::Bug)[http://github.com/brynary/rack-bug] is amazingly great.
May 25, 2009 at 3:52 am