ActiveSupport Notifications
Rails has a very nice way to attach and monitor everything you may wish for. The name of it is activesupport notifications. With notifications, you can simply create an initializer and set it to monitor whatever you wish. There are many events such as an activerecord load, a cache reading or expiring, render complete and each one will give you useful informations like render view time, db time etc. You can check the perfect guide for the events that exists already, but the notifications have another super power: you can create your own notifications.There are many guides, tutorials and a lovely railscast how you can do that. In this post, I will focus mainly on the already existing events and how you can use them to create a basic monitoring.
A basic log / monitoring
I wanted to search for slow queries, for actions that take too much time either for rendering or for database and I wanted to count the number of queries of each action and log them. The app is a pretty big one, so I wanted to gather in one place all this valuable information. I know that the development sometimes hides these valuable informations and they appear on production. One way would be to use a gem or new relic, but it is so easy to do it with the activesupport notifications that I just hack it around.So I created an initializer, I throw it inside the config/initializers folder and I let the magic to start. Here is the initializer: The code is pretty straight forward, I have two notifications, the first one is just counting the number of queries that comes from the code and stores them in a temporary variable. The second one is checking if there are more than 10 queries, it writes the information about the action inside the slow.log file and it also checks the database and the render time not to pass the 5 seconds. If they pass it, it will write the event inside the file. That's a pretty basic example of what you can do with the notifications, you can also create your own custom events and track them whenever you want.