Skip to content

Instantly share code, notes, and snippets.

@genewoo
Created September 10, 2013 05:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save genewoo/6505291 to your computer and use it in GitHub Desktop.
Save genewoo/6505291 to your computer and use it in GitHub Desktop.
A simple rack to log api performance.
class APIProfiler
def initialize(app, config = {})
@app = app
# default print out log to STDOUT, otherwise you can inject rails logger
@config = config
@config[:logger] = Logger.new(STDOUT) unless config[:logger]
@config[:log_level] = :info unless config[:logger_level]
@config[:filter] = lambda { false } unless config[:filter] #turn off by default
end
=begin
def initialize(app, config = {})
@app = app
@config = config
# @config[:size_threshold] = 20000 unless config[:size_threshold]
@config[:time_threshold] = 5000 unless config[:time_threshold]
# default print out log to STDOUT, otherwise you can inject rails logger
@config[:logger] = Logger.new(STDOUT) unless config[:logger]
@config[:log_level] = :info unless config[:logger_level]
end
=end
def call(env)
dup._call(env)
end
def _call(env)
@status, @headers, @response = @app.call(env)
# only time is default setted
_log(env) if @config[:filter].call(env, @status, @headers, @response)
[@status, @headers, self]
end
def _log(env)
@config[:logger].send @config[:log_level], "!! SLOW | #{@headers['X-Runtime'].to_i} | #{env['REQUEST_METHOD']} | #{env['PATH_INFO']} | #{env['rack.request.form_vars']}"
end
def each(&block)
@response.each(&block)
end
def to_s
end
end
config.middleware.insert_after ActionController::Failsafe, 'APIProfiler', {
:logger => config.logger,
:filter => lambda { |env, status, headers, response| headers['X-Runtime'].to_i > 500 }
} unless RAILS_ENV == 'production'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment