如何记录启动rails应用程序所花费的时间

fivyi3re  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(222)

在rails应用程序准备好服务请求之前,我如何记录它的启动持续时间?
通过添加 puts "Rails app booted in #{(boot_start - Time.now)} seconds" 在boot.rb'中,无法按预期工作。


# config/boot.rb

boot_start = Time.now

require "bundler/setup"
require "bootsnap/setup" if ENV["RAILS_ENV"] == "development"

puts "Rails app booted in #{(boot_start - Time.now)} seconds"

我需要的是
使用环境中定义的rails.logger打印日志项
尽可能准确(特别是,包括要求所有宝石所需的时间,最好包括https://guides.rubyonrails.org/initialization.html)
请注意,我上面提到的朴素方法打印web服务器实际启动之前的持续时间:

app_1       | Database 'XXX_staging' already exists
app_1       | Rails app booted in -1.2772e-05 seconds # Not only it appears before the server is ready
app_1       | Rails app booted in -1.01e-05 seconds   # But is also duplicated for some reason
app_1       | => Booting Puma
app_1       | => Rails 6.1.3.2 application starting in staging
app_1       | => Run `bin/rails server --help` for more startup options
app_1       | [12] Puma starting in cluster mode...
app_1       | [12] * Puma version: 5.3.1 (ruby 3.0.1-p64) ("Sweetnighter")
app_1       | [12] *  Min threads: 5
app_1       | [12] *  Max threads: 5
app_1       | [12] *  Environment: staging
app_1       | [12] *   Master PID: 12
app_1       | [12] *      Workers: 2
app_1       | [12] *     Restarts: (✔) hot (✖) phased
app_1       | [12] * Preloading application
app_1       | [12] * Listening on http://0.0.0.0:3000

我知道web服务器是异步启动的,测量方法将与用于运行应用程序的实际web服务器(在本例中为puma)耦合,但是使用任何web服务器实现这一点的示例可能会很有用。

pw136qt2

pw136qt21#

您可以将以下代码添加到 profile/boot.rb 然后跑 time bundle exec rake environment | sort :


# config/boot.rb

require 'benchmark'

def require(file_name)
  result = nil

  time = Benchmark.realtime do
    result = super
  end

  if time > 0.1
    puts "#{time} #{file_name}"
  end

  result
end

它应该为您提供与此类似的输出:

0.16465099999913946 ruby_parser
0.1686829999962356 sprockets/railtie
0.1764029999903869 rails
0.2461370000091847 pg_ext
0.24949699998251162 pg
0.26813800001400523 active_record/connection_adapters/postgresql_adapter
0.32413899997482076 mimemagic
0.3775960000057239 active_record/connection_adapters/postgis_adapter
0.4651059999887366 rails/all
0.549659000011161 rubocop
7.2341489999962505 /Users/leo/code/Flatlooker/config/environment.rb
bundle exec rake environment  7,05s user 2,82s system 67% cpu 14,615 total
sort  0,00s user 0,00s system 0% cpu 14,615 total

另一个很好的选择是gem bumbler
归功于https://mildlyinternet.com/code/profiling-rails-boot-time.html

相关问题