【发布时间】:2016-09-16 13:18:24
【问题描述】:
我有一个使用 puma 服务器运行的 rails 应用程序。有什么办法,我们可以看到当前应用程序中使用了多少线程?
【问题讨论】:
标签: ruby-on-rails puma
我有一个使用 puma 服务器运行的 rails 应用程序。有什么办法,我们可以看到当前应用程序中使用了多少线程?
【问题讨论】:
标签: ruby-on-rails puma
前段时间我也在想同样的事情,然后遇到了这个issue。作者包括了他们最终用来收集这些统计数据的代码:
module PumaThreadLogger
def initialize *args
ret = super *args
Thread.new do
while true
# Every X seconds, write out what the state of this dyno is in a format that Librato understands.
sleep 5
thread_count = 0
backlog = 0
waiting = 0
# I don't do the logging or string stuff inside of the mutex. I want to get out of there as fast as possible
@mutex.synchronize {
thread_count = @workers.size
backlog = @todo.size
waiting = @waiting
}
# For some reason, even a single Puma server (not clustered) has two booted ThreadPools.
# One of them is empty, and the other is actually doing work
# The check above ignores the empty one
if (thread_count > 0)
# It might be cool if we knew the Puma worker index for this worker, but that didn't look easy to me.
# The good news: By using the PID we can differentiate two different workers on two different dynos with the same name
# (which might happen if one is shutting down and the other is starting)
source_name = "#{Process.pid}"
# If we have a dyno name, prepend it to the source to make it easier to group in the log output
dyno_name = ENV['DYNO']
if (dyno_name)
source_name="#{dyno_name}."+source_name
end
msg = "source=#{source_name} "
msg += "sample#puma.backlog=#{backlog} sample#puma.active_connections=#{thread_count - waiting} sample#puma.total_threads=#{thread_count}"
Rails.logger.info msg
end
end
end
ret
end
end
module Puma
class ThreadPool
prepend PumaThreadLogger
end
end
此代码包含特定于 heroku 的逻辑,但收集 @workers.size 并记录它的核心将在任何环境中工作。
【讨论】: