O Active Support é parte do núcleo do Rails, e provê extensões, utilidades e outros itens à linguagem Ruby. Uma das coisas fornecidas é uma API para instrumentação, que pode ser usada em uma aplicação para medir certas ações internas do código Ruby, como por exemplo, ações da sua aplicação Rails ou do framework em si. A instrumentação não é limitada somente ao Rails, podendo também ser usada de forma independente em outros scripts Ruby.
Neste guia, você aprenderá como usar a API de instrumentação do Active Support, para medir eventos internos da sua aplicação Rails e de outros códigos Ruby.
Ao terminar de ler este guia, você saberá:
O que a instrumentação fornece.
Como adicionar um subscriber (ou observador) à um hook.
Os hooks internos do Rails, próprios para instrumentação.
Como criar sua própria implementação de instrumentação.
A API de instrumentação fornecida pelo Active Support permite que desenvolvedores exponham hooks para outros desenvolvedores utilizarem. Existem diversos destes hooks embutidos no framework Rails. Com essa API, os desenvolvedores podem escolher serem notificados quando certos eventos ocorrerem nas suas aplicações Rails ou em outros códigos em Ruby.
Por exemplo, existe um hook do Active Record que é chamado todas as vezes que uma query SQL é executada no banco.
Um subscriber (ou observador) pode se inscrever à este hook, e assim, observar o número de queries feitas durante uma certa ação. Durante a execução de uma das actions de um controller, existe também um hook que permite, por exemplo, monitorar a duração desta ação.
Subscribing to an event is easy. Use ActiveSupport::Notifications.subscribe with a block to
listen to any notification.
The block receives the following arguments:
The name of the event
Time when it started
Time when it finished
A unique ID for the instrumenter that fired the event
The payload (described in future sections)
ActiveSupport::Notifications.subscribe"process_action.action_controller"do|name,started,finished,unique_id,data|# your own custom stuffRails.logger.info"#{name} Received! (started: #{started}, finished: #{finished})"# process_action.action_controller Received (started: 2019-05-05 13:43:57 -0800, finished: 2019-05-05 13:43:58 -0800)end
If you are concerned about the accuracy of started and finished to compute a precise elapsed time then use ActiveSupport::Notifications.monotonic_subscribe. The given block would receive the same arguments as above but the started and finished will have values with an accurate monotonic time instead of wall-clock time.
ActiveSupport::Notifications.monotonic_subscribe"process_action.action_controller"do|name,started,finished,unique_id,data|# your own custom stuffRails.logger.info"#{name} Received! (started: #{started}, finished: #{finished})"# process_action.action_controller Received (started: 1560978.425334, finished: 1560979.429234)end
Defining all those block arguments each time can be tedious. You can easily create an ActiveSupport::Notifications::Event
from block arguments like this:
ActiveSupport::Notifications.subscribe"process_action.action_controller"do|*args|event=ActiveSupport::Notifications::Event.new*argsevent.name# => "process_action.action_controller"event.duration# => 10 (in milliseconds)event.payload# => {:extra=>information}Rails.logger.info"#{event} Received!"end
You may also pass a block that accepts only one argument, and it will receive an event object:
ActiveSupport::Notifications.subscribe"process_action.action_controller"do|event|event.name# => "process_action.action_controller"event.duration# => 10 (in milliseconds)event.payload# => {:extra=>information}Rails.logger.info"#{event} Received!"end
Most times you only care about the data itself. Here is a shortcut to just get the data.
You may also subscribe to events matching a regular expression. This enables you to subscribe to
multiple events at once. Here's how to subscribe to everything from ActionController.
ActiveSupport::Notifications.subscribe/action_controller/do|*args|# inspect all ActionController eventsend
Adding your own events is easy as well. ActiveSupport::Notifications will take care of
all the heavy lifting for you. Simply call instrument with a name, payload and a block.
The notification will be sent after the block returns. ActiveSupport will generate the start and end times
and add the instrumenter's unique ID. All data passed into the instrument call will make
it into the payload.
Here's an example:
ActiveSupport::Notifications.instrument"my.custom.event",this: :datado# do your custom stuff hereend
You also have the option to call instrument without passing a block. This lets you leverage the
instrumentation infrastructure for other messaging uses.
You should follow Rails conventions when defining your own events. The format is: event.library.
If your application is sending Tweets, you should create an event named tweet.twitter.
Feedback
Você é incentivado a ajudar a melhorar a qualidade deste guia.
Por favor, contribua caso veja quaisquer erros, inclusive erros de digitação.
Para começar, você pode ler nossa sessão de contribuindo com a documentação.
Você também pode encontrar conteúdo incompleto ou coisas que não estão atualizadas.
Por favor, adicione qualquer documentação em falta na main do Rails. Certifique-se de checar o
Edge Guides (en-US) primeiro para verificar
se o problema já foi resolvido ou não no branch main.
Verifique as Diretrizes do Guia Ruby on Rails
para estilo e convenções.
Se, por qualquer motivo, você encontrar algo para consertar, mas não conseguir consertá-lo, por favor
abra uma issue no nosso Guia.