Question

I am using the ruby gem rest-client with rest-client-components.

Rest-client-components enables request logging with Rack::CommonLogger.

The instructions for enabling it make use of STDOUT:

require 'restclient/components'
RestClient.enable Rack::CommonLogger, STDOUT

This works fine in development, but when I'm in production with Apache/Passenger (mod_rails), I don't see any messages from rest-client in production.log. Is there a way to integrate Rack::CommonLogger with the Rails log? Or at least to write it to a file? The former is more useful because it's easy to see the context, but the latter is better than nothing.

Thanks.

Was it helpful?

Solution

Here's the solution I came up with. Thanks to @crohr for pointing me in the right direction.

First, create a new Logger class. Rails defaults to ActiveSupport::BufferedLogger, so we'll extend that.

# lib/rest_client_logger.rb
class RestClientLogger < ActiveSupport::BufferedLogger
  def write(msg)
    add(INFO, msg)
  end
end

Then tell Rails to use your new logger.

# application.rb
log_file = File.open("log/#{Rails.env}.log", 'a')
log_file.sync = true  # turn on auto-flushing at the file level so we get complete messages
config.logger = RestClientLogger.new(log_file)
config.logger.auto_flushing = !Rails.env.production?  # turn off auto-flushing at the logger level in production for better performance

Finally, tell rest-client to use your new logger.

# config/initializers/rest_client.rb
RestClient.enable Rack::CommonLogger, Rails.logger

Limitations:

If you're using Rack::Cache with rest-client-components, this doesn't capture the cache messages.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top