如何记录 Rails 应用程序在准备好处理请求之前所花费的启动持续时间?
通过在 boot.rb` 中添加 puts "Rails app booted in #{(boot_start - Time.now)} 秒"
的简单方法无法按预期工作。
# 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 打印日志条目
- 尽可能准确(特别是,包括需要所有 gem 所花费的时间,最好是 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 服务器实现这一点的示例可能会很有用.
最佳答案
您可以将以下代码添加到您的 profile/boot.rb
中,然后运行 time bundle exec rakeenvironment |排序
:
# 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
Credit to https://mildlyinternet.com/code/profiling-rails-boot-time.html
关于ruby-on-rails - 如何记录启动 Rails 应用程序所需的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68366041/