尝试一下Rails6中新增的一些小功能88(ActiveSupport Instrumentation事件部分)

首先

尝试测试Rails 6中新增的第88个功能。这次是关于ActiveSupport Instrumentation(激活支持插件)事件的部分。
在Rails 6中,我们可以通过ActiveSupport Instrumentation(激活支持插件)获取事件的cpu_time(CPU时间),duration(持续时间),allocations(分配的对象数)等信息。

我已确认在Ruby 2.6.4和Rails 6.0.0上。

$ rails --version
Rails 6.0.0

我們這次要建立 User 的 CRUD 操作,並獲取每個控制器執行動作時的信息,輸出到日誌中。

创建项目

$ rails new rails_sandbox
$ cd rails_sandbox

创建用户的CRUD操作

我将创建具有名称字段的用户的CRUD功能。

$ bin/rails g scaffold User name

创建订阅者

创建一个继承自ActiveSupport::Subscriber类的ActionControllerSubscriber类,以便在日志中为每个动作输出cpu_time,duration和allocations。

class ActionControllerSubscriber < ActiveSupport::Subscriber
  attach_to :action_controller

  def process_action(event)
    action = "#{event.payload[:controller]}##{event.payload[:action]}"
    Rails.logger.info("#{action} cpu_time=#{event.cpu_time} duration=#{event.duration} allocations=#{event.allocations}")
  end
end

明确要求

为使ActionControllerSubscriber正常工作,在application_controller.rb中需要进行require操作。

class ApplicationController < ActionController::Base
end

require 'action_controller_subscriber'

用户完成注册等操作后可查看日志。

实际上,运行rails server并通过浏览器进行用户注册等操作,然后查看日志以确认。查看日志后,可以了解到输出了如下信息。

...
UsersController#index cpu_time=834.3827130000001 duration=838.4368330007419 allocations=1237659
...
UsersController#new cpu_time=15.012763999999956 duration=15.109344996744767 allocations=8648
...
UsersController#create cpu_time=9.577076000000018 duration=11.577429017052054 allocations=2932
...
UsersController#show cpu_time=12.707243000000146 duration=13.30683400738053 allocations=7172
...
UsersController#edit cpu_time=11.627590999999882 duration=11.854875017888844 allocations=7326
...
UsersController#update cpu_time=7.077903999999968 duration=9.087090991670266 allocations=3338
...
UsersController#show cpu_time=9.279210999999954 duration=11.935491987969726 allocations=6453
...
UsersController#index cpu_time=11.08482700000013 duration=12.24463598919101 allocations=6671
...
UsersController#destroy cpu_time=10.467926000000016 duration=23.146274004830047 allocations=2771
...
UsersController#index cpu_time=15.835581000000154 duration=17.571506003150716 allocations=6597

尝试过的酱料

以下是我尝试的源代码位置:
https://github.com/suketa/rails_sandbox/tree/try088_add_info_of_subscriber_events

请提供相关信息

    • What is new in Rails 6.0

 

    • Add cpu time, idle time, and allocations features to log subscriber events

 

    • Active Support Instrumentation

 

    • ActiveSupport::Subscriber

 

    Instrumenting Ruby on Rails with Prometheus

也许以下的文章可能与这篇文章有关。

    Rails6 のちょい足しな新機能を試す45(Allocations 編)
广告
将在 10 秒后关闭
bannerAds