April 19

0 comments

Site Monitoring with Ruby on Rails

By Christopher Mendla

April 19, 2016


Last Updated on September 15, 2020 by Christopher G Mendla

I needed a way to show the status (Up/down) of internal Ruby applications.  I found an answer on StackOverflow that pointed me in the right direction (Apologies that I can’t locate that post). . I modified that somewhat by putting it into a method and passing the site name to it.

If you put the following code in a controller, and all it as indicated in the remarks from your view, it will check the site and respond with UP or down.  I have a list of about a half dozen applications in a table with a status column.

NOTE – adding this WILL slow the page response where you are using multiple calls to check_apps. I’m noticing about a 2-3 second load time instead of an instantaneous load.

# ---------  check apps ----------------------
# This method will do a quick and dirty check 
# to see if a site is up or not.
# call the method with check_apps('http://www.sitename.com:port')
# the port is optional

helper_method :check_apps
def check_apps(site)
  require 'net/http'
  require 'json'
  status = '-'

  url = URI.parse(site)    
  req = Net::HTTP::Get.new(url.to_s)

  begin
    res = Net::HTTP.start(url.host, url.port) do |http|                      
      http.request(req)
      status = "UP"
    end
  rescue
    status = 'down'
  end
  return status

end

Ruby 2.x/Rails 4.x

Summary

This is useful if you are running a number of Rails apps within an organization and want to check to see if they are up and are limited as to budget and resources. If you have the resources and budget there are other options such as Newrelic

Christopher Mendla

About the author

Leave a Reply

Your email address will not be published. Required fields are marked

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}