Fork me on GitHub

More on watching ActiveRecord

Posted by Jamis on January 31, 2007 @ 12:50 PM

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!

Posted in Tips & Tricks

Comments

Have something to add? Click here to leave a comment.

31 Jan 2007

1. Kevin Marsh said...

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…

2. Erik Kastner said...

Amazingly cool hack. Thank you.

Any chance of getting log_to into core? :)

3. John said...

That’s a really nice trick!

4. UnderpantsGnome said...

Jamis- Very nice. Though sometimes you may not want color (it could happen, I guess), here’s a slight variation.


def log_to(stream, colorize=true)
  ActiveRecord::Base.logger = Logger.new(stream)
  ActiveRecord::Base.clear_active_connections!
  ActiveRecord::Base.colorize_logging = colorize
end

Michael-

5. Jamis said...

Nice variation, UnderpantsGnome. I’m adding that to my own local copy, since I personally hate the colorized logging. :)

01 Feb 2007

6. Kevin Barnes said...

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!

7. mathie said...

Nice! That’s another snippet added to my `~/.irbrc`.

05 Feb 2007

8. Tim Lucas said...

nice! Might give this a go to ensure eager loading is working from tests.