More on watching ActiveRecord
Remember Watching ActiveRecord Do Its Thing, where I talked about redirecting the log to STDOUT when using the console? I’ve got a new trick based on this that I’ve found quite helpful. Simply put the following snippet in your config/environment.rb
:
1 2 3 4 |
def log_to(stream) ActiveRecord::Base.logger = Logger.new(stream) ActiveRecord::Base.clear_active_connections! end |
Now, when you’re at the console, you can just do:
1 2 3 4 5 6 |
>> log_to STDOUT => ... >> Post.find(:first) Post Load (0.000138) SELECT * FROM posts LIMIT 1 => #<Post:0x1234 ...> >> |
The best part is, by clearing the active connections after setting the logger, you can change the logger at any time, even after you’ve made any number of find calls.
And, you can pass your own stream objects into it:
1 2 3 4 5 6 7 8 9 |
>> buffer = StringIO.new => ... >> log_to buffer => ... >> Post.find(:first) => #<Post:0x1234 ...> >> p buffer.string => " \e[4;35;1mPost Load (0.000138)\e[0m \e[0mSELECT * FROM posts LIMIT 1\e[0m\n" >> |
Why would you want to do this? Well, for one thing, you can use log_to in your tests, and make sure that sensitive things like credit card numbers aren’t being written to your logs. Or, you can use this in tests to make sure that your latest optimization really does reduce the number of queries made to the database.
Good fun!
Reader Comments
Pretty clever hack, and it made me realize that AR alternates syntax highlighting. Every other query is either pink or cyan. Never really thought about it before…
31 Jan 2007
Amazingly cool hack. Thank you.
Any chance of getting log_to into core? :)
31 Jan 2007
That’s a really nice trick!
31 Jan 2007
Jamis- Very nice. Though sometimes you may not want color (it could happen, I guess), here’s a slight variation.
Michael-
31 Jan 2007
Nice variation, UnderpantsGnome. I’m adding that to my own local copy, since I personally hate the colorized logging. :)
31 Jan 2007
Building on UG’s, default the stream to STDOUT in the method definition, since that’s probably what you want most of the time.
Jamis, as always, great stuff!
1 Feb 2007
Nice! That’s another snippet added to my `~/.irbrc`.
1 Feb 2007
nice! Might give this a go to ensure eager loading is working from tests.
5 Feb 2007