Created
April 17, 2015 21:56
-
-
Save lwoodson/ec0bd1e6d2235b48fdb1 to your computer and use it in GitHub Desktop.
Instrument HTTP calls made with Net::HTTP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
HTTP_LOG_PATH = File.expand_path("~/http.log") | |
FileUtils.rm_f(HTTP_LOG_PATH) | |
module NetInstrumentation | |
def self.included(base) | |
puts "Writing HTTP out to ~/http.log" | |
base.send(:alias_method, :__original_request, :request) | |
base.send(:alias_method, :request, :__logged_request) | |
end | |
def __logged_request(*args, &block) | |
request = args.first | |
request_data = JSON.parse(request.to_json) | |
request_data[:uri] = request.uri | |
request_data[:path] = request.path | |
request_data[:body] = request.body | |
return __original_request(*args, &block).tap do |response| | |
response_data = JSON.parse(response.to_json) | |
response_data[:code] = response.code | |
response_data[:message] = response.message | |
response_data[:body] = response.body | |
data = {request: request_data, response: response_data}.to_json | |
__logger.info(data) | |
end | |
end | |
def __logger | |
@__logger ||= Logger.new(HTTP_LOG_PATH) | |
end | |
end | |
Net::HTTP.send(:include, NetInstrumentation) | |
def http_log | |
File.readlines(HTTP_LOG_PATH).map do |line| | |
JSON.parse(line) rescue nil | |
end.compact | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line 17 wants to make my eyes bleed.
return magic.tap do |wtf|
hahaha