Report rake (>=0.9) exceptions to NewRelic

Posted by Anton Katunin on 8 August 2013
Tags: code, rails, exception, rake, newrelic

NewRelic service is great for application monitoring and errors tracking. However it doesn't track rake exceptions by default. You can use AirBrake gem and service, but sometimes it's too much for you. Fortunately with a bit of ruby it's easy to do it yourself.

Create a small module to hook into rake library at lib/rake_notifier.rb

module RakeNotifier
  def self.included(klass)
    klass.class_eval do
      alias_method :display_error_message_without_log, :display_error_message
      alias_method :display_error_message, :display_error_message_with_log
    end
  end
  
  def display_error_message_with_log(ex)
    ::NewRelic::Agent.notice_error(ex)
    display_error_message_without_log(ex)
  end
end

And then hook it up in the rails initialiser config/initializers/rake_notifier_hook.rb

if defined?(::Rake)
  Rake.application.instance_eval do
    class << self
      include RakeNotifier
    end
  end
end

That's it, now you will see rake exceptions at your NewRelic Errors view.