views:

25

answers:

3

I want to install a logger so that I can dump all executed SQL of my rails application. Problem is, such logger is associated with AbstractAdapter which initialized very soon under test mode, and thus cannot be set by my initializer code. I try to put

ActiveRecord::Base.logger = MyCustomLogger.new(STDOUT) 

in the end of environment.rb like someone advised but it only works when being run in console environment (kicked by script/console), not when run under test mode. I wonder if there is any way to config such logger so that I will sure to be invoked under any environment (test, development, production, console)

+1  A: 

Creating the logger in config/environment.rb should work. I get SQL logging on standard output when I run unit tests if I put the following line in either config/environment.rb or config/environments/test.rb:

ActiveRecord::Base.logger = Logger.new(STDOUT)

Does your MyCustomLogger class do anything special that causes it to fail during tests? Does it work better if you use Logger.new(STDOUT) instead?

Pär Wieslander
A: 

In test/test_helper.rb, before loading config/environment.rb, add:

RAILS_DEFAULT_LOGGER = MyCustomLogger.new(STDOUT)

Relevant code in railties for 2.3 railties/lib/initializer.rb#L35. Not sure how to do it with Rails 3.0 yet. It looks like you need to call Rails#logger=, but I can't find a good spot for it yet.

François Beausoleil
A: 

The best way as far as I can found is to put such code in initializers folder. This way, regardless of the running environment, the logger is always properly installed. And no, on my mac osx Rails 2.3.2 on ruby 1.8.7, if I put ActiveRecord::Base.logger=... inside environment.rb then the logger is not properly installed, since the logger that the Sql Connection used to dump SQL was installed and cached before that.

Phương Nguyễn