Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log SQL queries during rake tasks

Similar to 'rails server' that prints every SQL query executed I would like to do the same for rake tasks.

What is the best way to achieve that?

like image 852
mbdev Avatar asked Nov 23 '11 21:11

mbdev


5 Answers

Depending on your environment, Rake will log sql queries just like any Rails process will & in the same logfile. So on your dev box, check your log/development.log file - it will contain your Rake task's queries. If you want queries logged in production, set the log level in your Rake task to DEBUG, and make sure the rake task depends on :environment.

desc "Task with SQL logging"
task :test_log => :environment do
  Rails.logger.level = Logger::DEBUG
  Your code here...
end
like image 129
simianarmy Avatar answered Nov 02 '22 11:11

simianarmy


Proper answer is to put this at the beginning of rake task:

ActiveRecord::Base.logger = Logger.new STDOUT
like image 20
Daniel Garmoshka Avatar answered Nov 02 '22 11:11

Daniel Garmoshka


rake db:migrate  --trace

The --trace will show details

like image 5
drhenner Avatar answered Nov 02 '22 11:11

drhenner


echo '' > log/development.log
rake db:migrate:redo VERSION=20141017153933
cat log/development.log
like image 4
Benjamin Crouzier Avatar answered Nov 02 '22 12:11

Benjamin Crouzier


I tried the above and couldn't get it to work. Syntax was fine, no errors, but no sql came to stdout (or the log). I'm using rails 3.2. I'm also running in a production environment.

To see the sql queries generated by my rake tasks, I used the technique found at http://eewang.github.io/blog/2013/07/29/how-to-use-rake-tasks-to-generate-migration-sql/

In particular, I just inserted this block in my task before the find() statements that generated the SQL queries I was intersted in:

  ActiveRecord::Base.connection.class.class_eval do
    # alias the adapter's execute for later use
    alias :old_execute :execute

    # define our own execute
    def execute(sql, name = nil)
      print "===== #{sql}\n"
      old_execute sql, name
    end
  end

Then I could see the SQL on stdout. This is not my code - Eugene Wang came up with this technique.

like image 1
Don Law Avatar answered Nov 02 '22 12:11

Don Law