Skip to content

Instantly share code, notes, and snippets.

@simran-sawhney
Last active September 30, 2022 06:23
Show Gist options
  • Save simran-sawhney/e3845ba6c066898774f11dd8efcb9054 to your computer and use it in GitHub Desktop.
Save simran-sawhney/e3845ba6c066898774f11dd8efcb9054 to your computer and use it in GitHub Desktop.
Ruby-HTTParty-Api-Logging
# The following gist is useful if you want to log the API Requests and this is achieved using the following Monkey Patching script
# monkey patching HTTParty to log api request
class HTTParty::Request
def perform(&block)
validate
setup_raw_request
chunked_body = nil
current_http = http
# saving the time of the request to start
started_on = Time.now
self.last_response = current_http.request(@raw_request) do |http_response|
if block
chunks = []
http_response.read_body do |fragment|
encoded_fragment = encode_text(fragment, http_response['content-type'])
chunks << encoded_fragment if !options[:stream_body]
block.call ResponseFragment.new(encoded_fragment, http_response, current_http)
end
chunked_body = chunks.join
end
end
handle_host_redirection if response_redirects?
result = handle_unauthorized
result ||= handle_response(chunked_body, &block)
# logging monkey patching
log_db(options, @raw_request, result, started_on, Time.now, uri)
result
end
def log_db(options, raw_request, result, started_on, ended_on, uri)
params = {
request_body: (raw_request&.body rescue nil),
request_method: (raw_request&.method rescue nil),
request_headers: (options[:headers].to_json rescue nil),
request_path: (raw_request&.path rescue nil),
request_url: (uri&.to_s rescue nil),
response_body: (result&.response&.body rescue nil),
response_code: (result&.response&.code rescue nil),
response_headers: (result&.headers.to_json rescue nil),
host: (JSON.parse(raw_request.to_json)["host"][0] rescue nil),
started_on: (started_on rescue nil),
ended_on: (ended_on rescue nil),
time_spent: (ended_on - started_on rescue nil)
}
# Insert using job so not to delay the request call timings
Resque.enqueue(ApiRequestLogJob, params)
rescue Exception => e
Rollbar.error("HTTParty Log Db Error", message: e.message)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment