Rabu, 30 November 2011

Logging external http api calls in Rails log

Rabu, 30 November 2011

Http api calls are pretty similar to SQL queries - they query data from external source to ruby code workspace. So I think it's a good idea to log them just like ActiveRecord does with SQL queries.

  Location Load (25.1ms)   SELECT * FROM "locations" WHERE ("locations"."id" = 2548) ORDER BY title




This simple peace of code could be very helpful in case of debugging the HTTP api:
Log external http calls in rails log

Screenshot


Want to show the most interesting part:
  def request(request, body = nil, &block)
time = Time.now
response = request_without_log(request, body, &block)
response
ensure
if self.started?
url = "http#{"s" if self.use_ssl?}://#{self.address}:#{self.port}#{request.path}"
ofset = Time.now - time
rails_log("HTTP #{request.method} (%0.2fms)" % (ofset * 1000), url)
rails_log("POST params", request.body) if request.is_a?(::Net::HTTP::Post)
if defined?(response) && response
rails_log("Response status", "#{response.class} (#{response.code})") 
body = response.body
rails_log("Response body", body) unless body.is_a?(Net::ReadAdapter)
end
end


Pay attention on how ensure works with context.
The response local variable defined inside of def and ensure, but still accessible in after ensure if there was no exception inside of request_without_log. This would never be possible in static programming language.


Related Posts :

0 komentar:

Poskan Komentar

Related Posts Plugin for WordPress, Blogger...
 

HOT NEWS

HOT STORIES

HOT ACTRESS


BACA BERITA is proudly powered by Blogger.com | Template by Blog Zone