Http api calls are pretty similar to SQL queries – they query data from external source make it available in ruby. So I think it’s a good idea to track them in the Rails logger just like ActiveRecord does with SQL queries.
This simple peace of code could be very helpful in case of debugging HTTP api. Installation is pretty simple:
gem install http_logger
require 'http_logger' Net::HTTP.logger = Logger.new(...) Net::HTTP.colorize = true
In rails you don’t have to do anything, as defaults are:
# Net::HTTP.logger = Rails.logger if defined?(Rails). # Net::HTTP.colorize = true
TODO for v2:
Completed 200 OK in 150ms (Views: 13.5ms | ActiveRecord: 0.0ms | Net::HTTP: 115.5ms)
Offtop for ruby lovers
Want to show the most interesting part in the source code:
def request(request, body = nil, &block) ... response = request_without_log(request, body, &block) ensure ...... if defined?(response) rails_log("Response body", response.body) unless response.body.is_a?(Net::ReadAdapter) end end
Pay attention on how ensure
works with context. The response
local variable defined inside of def
, but still accessible after ensure if there was no exception inside of request_without_log
. This would never be possible in static programming language.