Logging with Sinatra and Passenger – Another try
Thanks to the requests a few enterprising commenters, I’ve looked into logging with mod_rails and Sinatra a little closer. My last attempt was close, but not quite. If you swap out the config.ru file for this version, logging will work correctly.
require 'sinatra/lib/sinatra.rb' require 'rubygems' Sinatra::Application.default_options.merge!( :run => false, :env => :production, :raise_errors => true ) log = File.new("sinatra.log", "a") STDOUT.reopen(log) STDERR.reopen(log) require 'test.rb' run Sinatra.application
Some interesting things to note
- Open the file with “a” instead of “w”. Append rather than open means that restarts and the like won’t reset the log file. A fun fact about passenger: it seems that passenger restarts your application if you return a 500 response code. The append means that we don’t blow away the log file right away after that.
- raise_errors => true. This is important. When Sinatra is in production mode, it just stops throwing errors, and instead shows a simple “Server Error” page. This setting re-enables the exception throwing.
At least one more thing to look into:: Nice error pages. How can we have good error logging AND good error pages?
October 10th, 2008 at 3:34 pm
I’ve found using thin’s logging to be the best.
Just run:
thin start -R mysinatraapp.rb -D -l logs/mysinatraapp.log
The -D will give you verbose debugging information for internal exceptions
December 21st, 2008 at 11:41 am
[…] out. It would be nice to log these to a file, and we can do that as well in config.ru (based on this tip from Chris Schneider). We’ll also need to turn error raising back on, since by default […]
March 6th, 2009 at 1:41 am
[…] to John Nunemaker and Chris Schneider for the […]
June 27th, 2009 at 3:57 am
Great tip, thanks!
It was working fine for me with passenger 2.0.6, but I just upgraded to passenger 2.2.4 and found that my application wouldn’t start. I was presented with the following error:
Error message:
not opened for reading
Exception class:
IOError
I managed to fix this, by changing the mode from “a” to “a+”, as follows:
log = File.new(“sinatra.log”, “a+”)
Now everything is rosie again.
August 30th, 2010 at 12:42 pm
If you want to follow your logs real-time using tail, add:
log.sync = true