/mongo_db_logger

Ruby Mongo DB Logger for Rails - centralized logging for rails apps in MongoDB

Primary LanguageRubyMIT LicenseMIT

MongoDbLogger

Log to MongoDB from a Rails app

Usage:

  1. add the following line to your ApplicationController:

include MongoDBLogging

  1. configure specific environments to use the MongoLogger (in config/#{environment}.rb):

config.logger = MongoLogger.new

  1. add mongo settings for each environment in which you want to use MongoDB for logging:

development:
  adapter: mysql
  database: my_app_development
  user: root
  mongo:
    database: my_app
    capsize: <%= 10.megabytes %>
    host: localhost
    port: 27017

With that in place, a new MongoDB document (record) will be created for each request and, by default will record the following information: Runtime, IP Address, Request Time, Controller, Action, Params and All messages sent to the logger. The structure of the Mongo document looks something like this:


{
  'controller'    : controller_name,
  'action'        : action_name,
  'ip'            : ip_address,
  'runtime'       : runtime,
  'request_time'  : time_of_request,
  'params'        : { }
  'messages'      : {
                      'info'  : [ ],
                      'debug' : [ ],
                      'error' : [ ],
                      'warn'  : [ ],
                      'fatal' : [ ]
                    }
}

Beyond that, if you want to add extra information to the base of the document (let’s say something like user_guid on every request that it’s available), you can just call the Rails.logger.add_metadata method on your logger like so:


# make sure we're using the MongoLogger in this environment
if Rails.logger.respond_to?(:add_metadata)
  Rails.logger.add_metadata(:user_guid => @user_guid)
end

And now, for a couple quick examples on getting ahold of this log data… First, here’s how to get a handle on the MongoDB from within a Rails console:


>> db = MongoLogger.mongo_connection
=> #<Mongo::DB:0x102f19ac0 @slave_ok=nil, @name="my_app" ... >

>> collection = db[MongoLogger.mongo_collection_name]
=> #<Mongo::Collection:0x1031b3ee8 @name="development_log" ... >

Once you’ve got the collection, you can find all requests for a specific user (with guid):


>> cursor = collection.find(:user_guid => '12355')
=> #<Mongo::Cursor:0x1031a3e30 ... >
>> cursor.count
=> 5

Find all requests that took more that one second to complete:


>> collection.find({:runtime => {'$gt' => 1000}}).count
=> 3

Find all requests that passed a parameter with a certain value:


>> collection.find({'params.currency' => 'USD'}).count
=> 22

Copyright (c) 2009 Phil Burrows, released under the MIT license