Monkey Patch Du Jour

May 24, 2009 Alex Chaffee

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

About the Author

Biography

More Content by Alex Chaffee
Previous
Some Web Ops Resources
Some Web Ops Resources

A laundry list of stuff I've come across / been pointed to lately. What are your favorites (i.e. comments,...

Next
Javascript Snacks, Nibble #1: RTE/WYSIWYG is Built in to your Browser
Javascript Snacks, Nibble #1: RTE/WYSIWYG is Built in to your Browser

The Label "Tasty! No Trans-Fats." I've now worked with a number clients who have a taste for a "ric...

Enter curious. Exit smarter.

Learn More