yabeda-rails浅析
继承
::Rails::Railtie
,使其在rails项目中自动执行::Yabeda::Rails.install!
# yabeda-rails-0.8.1/lib/yabeda/rails/railtie.rb
module Yabeda
module Rails
class Railtie < ::Rails::Railtie
def rails_server?
::Rails.const_defined?(:Server)
end
def puma_server?
::Rails.const_defined?("Puma::CLI")
end
def unicorn_server?
::Rails.const_defined?("Unicorn::Launcher")
end
initializer "yabeda-rails.metrics" do
::Yabeda::Rails.install! if rails_server? || puma_server? || unicorn_server?
end
end
end
end
而
::Yabeda::Rails.install!
会使用[[ActiveSupport Notifications]]收集以下指标# yabeda-rails-0.8.1/lib/yabeda/rails.rb
def install!
Yabeda.configure do
config = Config.new
group :rails
counter :requests_total #...
histogram :request_duration # ...
histogram :view_runtime # ...
histogram :db_runtime # ...
# ...
ActiveSupport::Notifications.subscribe "process_action.action_controller" do |*args|
event = ActiveSupport::Notifications::Event.new(*args)
labels = {
# ...
}
labels.merge!(event.payload.slice(*Yabeda.default_tags.keys - labels.keys))
rails_requests_total.increment(labels)
rails_request_duration.measure(labels, Yabeda::Rails.ms2s(event.duration))
rails_view_runtime.measure(labels, Yabeda::Rails.ms2s(event.payload[:view_runtime]))
rails_db_runtime.measure(labels, Yabeda::Rails.ms2s(event.payload[:db_runtime]))
Yabeda::Rails.controller_handlers.each do |handler|
handler.call(event, labels)
end
end
end
end