Rails 12 Feb 2007 07:11 am

Flaming Hoops: Rails Logging Tricks

Many people enjoy the sideshow carnival cliche of mammals jumping through flaming hoops. It’s quick, it’s fun, and it invokes a harmless façade of danger. In that vein, this new series of hoop-vaulting articles will push against the bumper-guards of the average Ruby on Rails playground, exploring faux danger and hopefully providing some light entertainment.

This first batch of tips fiddles with unit test logging by tweaking the test/unit/test_helper.rb file. By default, when you run rake test:units from the top level directory of your Rails application, all logging output goes into log/test.log. If that’s not good enough, if you want a different name or location for your test output, the change is easy. Add this to the end of test_helper.rb:

TESTLOG = File.expandpath(”#{RAILSROOT}/log/flamey-test.log”) ActiveRecord::Base.logger = Logger.new(TESTLOG)

If you’re writing a standalone ActiveRecord application outside of a Rails environment, you’ll have to explicitly create and assign a logger yourself. The easiest solution is to pass Logger.new a simple file name.

ActiveRecord::Base.logger = Logger.new(”test.log”)

Unfortunately this will drop the log file into whichever relative directory you run the tests from. What you probably want is to anchor it to the test_helper.rb file (which you’ll also have to create yourself in a standalone application).

TESTLOG = File.expand_path(File.dirname(FILE) + “/test.log”) ActiveRecord::Base.logger = Logger.new(TESTLOG)

A slightly better place is in a log directory, sibling to the test directory:

TESTLOG = File.expand_path(File.dirname(FILE) + “/../log/test.log”) ActiveRecord::Base.logger = Logger.new(TESTLOG)

More tips on the flip side…

Another handy hoop trick is to provide a command-line switch for STDOUT logging. To send output to a file, invoke your tests as normal; to send output to the console, set LOG_STDOUT in your environment to anything, e.g. LOG_STDOUT=yes ruby test/my_test.rb.

TESTLOG = File.expandpath(File.dirname(FILE) + “/test.log”) ActiveRecord::Base.logger = ENV["LOGSTDOUT"] ? Logger.new(STDOUT) : Logger.new(TESTLOG)

Of course, there’s always the lower level logging properties. To turn off the special color markup (who on earth made that the default?!?):

ActiveRecord::Base.colorize_logging = false

To filter the logging output by severity level:

ActiveRecord::Base.logger.level = Logger::INFO

And finally, this line tags the log file (or console output) with a friendly banner whenever the test_helper.rb file is loaded, which amounts to every time you run the tests:

ActiveRecord::Base.logger.info( “#{”=”25} RUNNING UNIT TESTS #{”=”25}\n\t\t\t#{Time.now.to_s}\n#{”=”*70}”)

It looks like this:

========================= RUNNING UNIT TESTS =========================

Mon Feb 12 10:39:50 CST 2007

Have fun, and stay tuned for the next Hoop o’ fire.

Comments are closed.

Trackback This Post |