Skip to content

Instantly share code, notes, and snippets.

@cpetschnig
Created February 25, 2015 09:41
Show Gist options
  • Save cpetschnig/3124e228eef01679a971 to your computer and use it in GitHub Desktop.
Save cpetschnig/3124e228eef01679a971 to your computer and use it in GitHub Desktop.
Log more information about API request in your Rails application
# 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
@stephanschubert
Copy link

Sure about L31? I've seen requests going to api.sageone.com/v2/...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment