Last Updated: February 25, 2016
· whoward

Easy Airbrake error logging for simple ruby scripts

Add this code to any one-off scripts you might run without supervision (cron jobs are a great use case) and if an exception is raised while running it it will be logged to Airbrake. A good place to put this is in a shared "boot" script that any of your one-off scripts include.

# configure Airbrake and set it up to automatically 
# report any non-standard errors when the program 
# exits
Airbrake.configure do |config|
   config.api_key = "<your-project-key-here>"

# this is one way to get the environment your script 
# is running in, you can change out the body of this 
# method with whatever works well for you.
def project_environment
   require 'socket'
   Socket.gethostname == "<your-production-server-hostname-here>" ? "production" : "development"

at_exit do
   # SystemExit and Interrupt are normal exceptions 
   # that terminate the ruby process, ignore them
   if $! and not [SystemExit, Interrupt].include? $!.class
      params = {:argv => ARGV.join(" "), :script => $0}
      environment = project_environment

      if environment == "production"
         Airbrake.notify($!, :parameters => params, 
                             :environment_name => environment)

This is partly derived from a code example in @jeg2's "101 things you didn't know ruby could do" talk

This is my first protip: be nice!