Logging external http api calls in Rails log
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.
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:
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.
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.
Komentar
Posting Komentar