【问题标题】:How can I log the time taken to start a rails app如何记录启动 Rails 应用程序所花费的时间
【发布时间】:2021-09-22 17:20:17
【问题描述】:

如何记录 Rails 应用程序在准备好服务请求之前的启动持续时间?

在 boot.rb 中添加 puts "Rails app booted in #{(boot_start - Time.now)} seconds" 的幼稚方法无法按预期工作。

# 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"

我需要的是

请注意,我上面提到的幼稚方法会打印 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 服务器实现此目的的示例可能会很有用.

【问题讨论】:

  • 我会使用一个非常懒惰的解决方案:流式传输日志输出,并在打印 Listening on http://0.0.0.0:3000 时立即停止计时器。
  • 通过这种方式,您可以测量端到端的实际启动时间。您可以保证在启动服务器之前真正“启动时钟”(在一个单独的过程中!!),并且您可以保证在最后记录的 rails 指示“就绪”之后“停止时钟”。
  • 虽然本身不​​是答案,但您可能想看看bumbler

标签: ruby-on-rails ruby ruby-on-rails-6 puma


【解决方案1】:

您可以将以下代码添加到您的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

【讨论】:

  • 您能否证明您也在测量启动 HTTP 服务器所需的时间,直到应用程序“准备好服务请求”,正如我在原始问题中提到的那样?
猜你喜欢
  • 2014-02-20
  • 2013-09-17
  • 2021-01-22
  • 1970-01-01
  • 1970-01-01
  • 2017-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多