Skip to content

Instantly share code, notes, and snippets.

@tonyfg
Last active January 29, 2024 08:37
Show Gist options
  • Select an option

  • Save tonyfg/003430b8dd1d5df37c38814e17491132 to your computer and use it in GitHub Desktop.

Select an option

Save tonyfg/003430b8dd1d5df37c38814e17491132 to your computer and use it in GitHub Desktop.
Log Rails object allocations during a request
class ApplicationController < ActionController::Base
around_action :track_object_allocation
def allocation_logger
@@allocation_logger ||= begin
logger = Logger.new("#{Rails.root}/log/allocation_trace.log")
logger.formatter = proc { |_severity, _datetime, _progname, msg|
"#{msg}\n"
}
logger
end
end
def track_object_allocation
gc_stats = GC.stat
prev_allocated = gc_stats[:total_allocated_objects]
prev_freed = gc_stats[:total_freed_objects]
yield
gc_stats = GC.stat
post_allocated = gc_stats[:total_allocated_objects]
post_freed = gc_stats[:total_freed_objects]
allocation_logger.info(
"#{request.parameters['controller']}##{request.parameters['action']}."\
"#{request.format.to_sym} | "\
"Allocated: #{post_allocated - prev_allocated} | "\
"Freed: #{post_freed - prev_freed}"
)
end
end
# This will produce a log file in log/response_times.log with the following format:
# organizations#index.html | Allocated: 1806829 | Freed: 1476976
# organizations#index.json | Allocated: 24971059 | Freed: 10092833
# organizations#index.html | Allocated: 1773136 | Freed: 2924318
# organizations#index.html | Allocated: 1456358 | Freed: 3755718
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment