Rails Notifications: Subscribe to internal events
We’ll all agree that it is very useful to know how our application is performing in aim to: detect bottlenecks, generate statistics, measure metrics, etc. Rails 3 introduced a very easy mechanism to allow access for all internal notifications:
ActiveSupport::Notifications. It’s in the same way that Rails internally logs
More or less this mechanism works in the following way: given a code block, when the block finishes, an event is triggered to notify any report that is subscribed to it.
To take a first look, we’re going to print all notifications into the log file. We just need to subscribe to all notifications. For do this, add this piece of code to an initializer (/config/initializers/notifications.rb):
Restart the server and make a request. We’ll see those lines in the application log:
We may observe different kinds of notifications like:
Very useful the last one. This notification includes information such as: the params, the path, the view_runtime, the db_runtime…
We can subscribe for only one specific kind of notifications by filtering them. For do this, we’ll pass a parameter to
Another interesting idea would be to store notifications into our database in order to manage information easily.
We can implement a more complex solutions. For example: store data to Memcached or Redis, and bulk it into a persisted storage periodically. Any good idea across your mind.
Create custom notifications
We can create our own notifications and subscribe to them as well. For example:
There are some professional and well known tools to monitor our applications in production environment, like RPM New Relic, Librato Metrics, Riemann. Totally Right, full solutions and very liked, but this API helps us to build for example: a custom case study, a custom logging, a self-made usage statistics, alerting, etc. Cool!
Be sure to check out the official documentation for further information.