Rails console and ActiveRecord logger – Rails 3
Well, there are many many times (in fact always :P) that you want active record sql queries to log into STDOUT and especially when you are working in the rails console. I didn’t know how to do this and after a while of Google searching I stumbled upon this command that you type every time you open the rails console:
ActiveRecord::Base.logger = Logger.new(STDOUT)
That was pretty sweet when I saw this little command working (my sql queries were shown into the console :)) but ended up a little annoying having to type this every time I open my console. The solution is apparent if you try this in a rails console
# rails c $0 # => "script/rails"
Thus inside the console the $0 has value "script/rails"
. Therefore inside your environment.rb file you can write:
if "script/rails" == $0 ActiveRecord::Base.logger = Logger.new(STDOUT) end
and get ActiveRecord sql queries to log to STDOUT everytime you use the console. If you don’t wrap ActiveRecord::Base.logger = Logger.new(STDOUT)
inside this if statement then you will always use STDOUT as the ActiveRecord logging and you don’t want that in any way!
Why not just include it in the `.railsrc` file? Like I do here: https://github.com/pjg/dotfiles/blob/master/.railsrc
Sure you can do that :)! The .railsrc is the way to go if you are involved in team work. Nice pointer though Pawel!