Created
May 28, 2016 13:39
-
-
Save arthurnn/40a3280488216d2741bfe50a36227178 to your computer and use it in GitHub Desktop.
Rails boot instrumentation
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
# Backport patch made on Rails 4.1 , to add instrumentation around the | |
# initializer load code. see https://github.com/rails/rails/pull/12859 | |
# Remove this patch once we are on Rails 4.1+ | |
Rails::Engine.class_eval do | |
if method_defined? :load_config_initializer | |
warn "[DEPRECATION] load_config_initializer patch can now be removed." | |
else | |
def load_config_initializer(initializer) | |
ActiveSupport::Notifications.instrument('load_config_initializer.railties', initializer: initializer) do | |
load(initializer) | |
end | |
end | |
def self.replace_initializer(name, on: self, &block) | |
if initializer = on.initializers.find { |ini| name == ini.name } | |
initializer.instance_variable_set(:@block, block) | |
end | |
end | |
replace_initializer :load_config_initializers do | |
config.paths["config/initializers"].existent.sort.each do |initializer| | |
load_config_initializer(initializer) | |
end | |
end | |
end | |
end | |
module RailsApplicationInstrumentation | |
class InitializerSubscriber | |
attr_reader :times | |
def initialize | |
@times = [] | |
end | |
def call(*args) | |
event = ActiveSupport::Notifications::Event.new(*args) | |
@times << [event.duration, event.payload[:initializer].to_s] | |
end | |
def total_time | |
@times.sum(&:first) | |
end | |
end | |
def self.included(base) | |
config = base.config | |
config.debug_boot = ENV['DEBUG_BOOT'] | |
if config.debug_boot | |
subs = InitializerSubscriber.new | |
ActiveSupport::Notifications.subscribe('load_config_initializer.railties', subs) | |
config.after_initialize do | |
puts "[DEBUG_BOOT] Slower initializers:" | |
subs.times.sort_by { |i| -i.first }.take(3).each do |a| | |
puts "[DEBUG_BOOT] #{a.last} loaded in #{a.first}ms" | |
end | |
puts "[DEBUG_BOOT] Time of initializers: #{subs.total_time}ms" | |
end | |
base.prepend PrependMethods | |
end | |
end | |
def initialize! | |
start = Time.now | |
super | |
after_time = (Time.now - start) * 1_000 | |
puts "[DEBUG_BOOT] Rails booted in #{after_time}ms" if config.debug_boot | |
end | |
module PrependMethods | |
def eager_load! | |
puts "[DEBUG_BOOT] Eager loading all classes." | |
super | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment