Rails MongoDB logging on Heroku with MongoHQ

I love Heroku but it only retains your last 100 lines of logs. To save your log output you need to store them outside of the service. MongoDB is “fantastic for logging” and Heroku’s MongoHQ add-on makes it easy to spin up a MongoDB instance. The first step is to add the MongoHQ add-on to your app:

$ heroku addons:add mongohq:free

You’ll need to include Ruby’s MongoDB driver Mongo in your .gems file:

mongodb-mongo --source gems.github.com

Next, install the mongo_db_logger plugin in your rails project (script/plugin install git://github.com/peburrows/mongo_db_logger.git) and include the library in your application controller:

class ApplicationController < ActionController::Base
include MongoDBLogging

helper :all # include all helpers, all the time
protect_from_forgery # See ActionController::RequestForgeryProtection for details

And then, to actually use it in your different environments, add the following line to your app’s "config/#{environment}.rb":

config.logger = MongoLogger.new

Once you’ve installed the plugin you will have to hard code connection information into the plugin. I edited mongo_logger.rb to connect to MongoDB via Heroku’s evironment variable MONGOHQ_URL

@mongo_collection_name = "#{Rails.env}_log"

uri = URI.parse(ENV['MONGOHQ_URL'])

@mongo_connection ||= Mongo::Connection.new(uri.host, uri.port, :auto_reconnect => true).db(uri.path.gsub(/^//, ''))

@mongo_connection.authenticate(uri.user, uri.password)

# setup the capped collection if it doesn't already exist
unless @mongo_connection.collection_names.include?(@mongo_collection_name)
@mongo_connection.create_collection(@mongo_collection_name, {:capped => true, :size => 10.megabytes})
rescue => e
puts "=> !! A connection to mongo could not be established - #{e.message} - the logger will function like a normal ActiveSupport::BufferedLogger !!"

To learn more about the mongo_db_logger plugin, read Phil Burrows’ article “Rails Logging with MongoDB”

Abi Noda is a software engineer at Doejo and partner at OrangeQC, a software as a service company offering quality control systems for hospitals, food and janitorial service companies. He is also a developer at Posy, the best online event planning software.

Filed in: Web Development