Created
December 10, 2012 01:43
-
-
Save dblock/4247912 to your computer and use it in GitHub Desktop.
API logger with Grape under Rails
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
class ApiLogger < Grape::Middleware::Base | |
def before | |
Rails.logger.info "[api] Requested: #{request_log_data.to_json}\n" + | |
"[api] #{response_log_data[:description]} #{response_log_data[:source_file]}:#{response_log_data[:source_line]}" | |
end | |
private | |
def request_log_data | |
request_data = { | |
method: env['REQUEST_METHOD'], | |
path: env['PATH_INFO'], | |
query: env['QUERY_STRING'] | |
} | |
request_data[:user_id] = current_user.id if current_user | |
request_data | |
end | |
def response_log_data | |
{ | |
description: env['api.endpoint'].options[:route_options][:description], | |
source_file: env['api.endpoint'].block.source_location[0][(Rails.root.to_s.length+1)..-1], | |
source_line: env['api.endpoint'].block.source_location[1] | |
} | |
end | |
end |
@hamin Yes, dirty... I found a nasty bug in this code:
# Rack::Utils.parse_query('♥')
# /.../vendor/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/utils.rb:92: warning: regexp match /.../n against to UTF-8 string
# => {"♥"=>nil}
# [2] pry(#<Backbone::ApiLogger>)> Rack::Utils.parse_query('%')
# ArgumentError: invalid %-encoding (%)
# from /home/xxx/.rvm/rubies/ruby-2.2.0/lib/ruby/2.2.0/uri/common.rb:382:in `decode_www_form_component'
so the percent sign has to be escaped too, in case somebody wants to use it
rack_input = rack_input.gsub("&", "%26").gsub("%", "%25")
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@aserafin -- can you specify where to put those two lines of code -- Ruby beginner here.