The maze book for programmers!
mazesforprogrammers.com

Algorithms, circle mazes, hex grids, masking, weaving, braiding, 3D and 4D grids, spheres, and more!

DRM-Free Ebook

The Buckblog

assorted ramblings by Jamis Buck

More on watching ActiveRecord

31 January 2007 — 1-minute read

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…

Amazingly cool hack. Thank you.

Any chance of getting log_to into core? :)

That’s a really nice trick!

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-

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

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!

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

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