Archive

Posts Tagged ‘webdev’

Logging exceptions to a file using Padrino

October 11, 2013 Leave a comment

You wouldn’t think this would be a very complex topic.  Something every web server should be pretty good at is letting you see the activity on your server and most importantly the exceptions your app is sure to run into in production.  Without that, it’s rather difficult to hunt down your problems.  From what I’ve found the typical way this is done is by your frontend, be that Thin or whatever redirecting stdout and stderr to their log files.  I find myself in a rather odd situation though, as I am deploying on Windows using Helicon Zoo.  No, Linux deployment is probably not an option for this particular situation.  Ok, so now Helicon does its thing pretty well, makes your Rack app show up in IIS as an app, etc.  Padrino logs its files ok, but exceptions are mysteriously lost to the void.  So what I came up with was to redirect $stdout and $stderr to the Padrino logger (at info and warn levels).  The idea came from this thread.

In my boot.rb file I add the following

 

Padrino.after_load do
  info_wrapper = IOLogWrapper.new(Padrino.logger, :info)
  warn_wrapper = IOLogWrapper.new(Padrino.logger, :warn)

  $stdout = info_wrapper
  $stderr = warn_wrapper
end

This wraps up the Padrino standard logger into something that can be assigned to $stdout, namely a subclass of IO. Here’s the IOLogWrapper class

class IOLogWrapper < IO
  def initialize(logger, level)
    @logger = logger

    case level
      when :info
        @method_to_call = @logger.method(:info)
      when :warn
        @method_to_call = @logger.method(:warn)
    end
  end

  def write(str)
    @method_to_call.call(str)
    return str.length
  end
end

Voila! Your exceptions are now logged as info and warning messages in your Padrino log file.

Advertisements
Categories: Development Tags: , ,