Skip to content

Instantly share code, notes, and snippets.

@dplummer
Created January 5, 2011 23:35
Show Gist options
  • Save dplummer/767233 to your computer and use it in GitHub Desktop.
Save dplummer/767233 to your computer and use it in GitHub Desktop.
Include in ApplicationController to bench calls and log them (like Rails does with View and DB)
module ExtendResponseTimeLogging
def self.included(base)
base.class_eval do
alias_method_chain :perform_action, :extra_benchmark
end
end
def bench(name, &block)
@additional_response_times[name] ||= 0.0
@additional_response_times[name] += Benchmark.ms {yield}
end
def perform_action_with_extra_benchmark
if logger
@additional_response_times = {}
ms = [Benchmark.ms { perform_action_without_benchmark }, 0.01].max
logging_view = defined?(@view_runtime)
logging_active_record = Object.const_defined?("ActiveRecord") && ActiveRecord::Base.connected?
log_message = 'Completed in %.0fms' % ms
if logging_view || logging_active_record || @additional_response_times.size > 0
log_message << " ("
log_message << view_runtime if logging_view
if logging_active_record
log_message << ", " if logging_view
log_message << active_record_runtime
end
if @additional_response_times.size > 0
@additional_response_times.each do |name, time|
log_message << ", "
log_message << '%s: %d' % [name, time]
end
end
log_message << ")"
end
log_message << " | #{response.status}"
log_message << " [#{complete_request_uri rescue "unknown"}]"
logger.info(log_message)
response.headers["X-Runtime"] = "%.0f" % ms
else
perform_action_without_benchmark
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment