Created
February 25, 2015 09:41
-
-
Save cpetschnig/3124e228eef01679a971 to your computer and use it in GitHub Desktop.
Log more information about API request in your Rails application
This file contains hidden or 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
# Put the following line into the config section in config/application.rb: | |
# | |
# config.middleware.use RackAPILogger | |
class RackAPILogger | |
def initialize(app) | |
@app = app | |
end | |
def call(env) | |
@request = Rack::Request.new(env) | |
if api_call? | |
Rails.logger.debug(Rack::Utils.parse_query(request_body)) | |
end | |
@app.call(env).tap do |app| | |
if api_call? | |
Rails.logger.debug(completed_message(app)) | |
if app.last.respond_to?(:body) | |
Rails.logger.debug("JSON result:") | |
hash = JSON.parse(app.last.body.first) | |
pretty = JSON.pretty_generate(hash) | |
Rails.logger.debug(pretty) | |
end | |
end | |
end | |
end | |
def api_call? | |
@request.path.start_with?("/api/") | |
end | |
def request_body | |
body = @request.body.readlines | |
@request.body.rewind | |
body.first | |
end | |
def completed_message(app) | |
"Completed API request with #{app.first} #{Rack::Utils::HTTP_STATUS_CODES[app.first]}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sure about L31? I've seen requests going to
api.sageone.com/v2/...