Rack::RequestStatisticTracker
Submitted by Thanatos at 09 Oct 13:09
About
RequestStatisticTracker
Track a particular set of analytics around requests (to Rails, at the moment) into a MongoDB document. The benefits of MongoDB for logging are relatively well espoused at this point.
It isn't super-portable, or remotely configurable, at the moment.
Usage
HowTo
Create a class RequestStatistic like the example given in the code. In fact, the example in the code should work perfectly.
Remember to require, and configure MongoMapper, as needed.
Then, a simple config.middleware.use "RequestStatisticTracker" in your Rails config/environment.rb file will set you up.
Querying for statistics is easy thanks to the MongoMapper RequestStatistic class. MongoMapper works very much like ActiveRecord.
Code
module Rack class RequestStatisticTracker def initialize(app) @app = app end def call(env) status, headers, response = @app.call(env) path = env['REQUEST_PATH'] || env['PATH_INFO'] format = format_from_content_type(headers['Content-Type']) track(env['REMOTE_ADDR'], headers['X-Runtime'], format, path) [status, headers, response] end private def format_from_content_type(type) type.nil? ? :html : Mime::Type.lookup(type.split(';').first).to_sym end def track(ip, runtime, format, path) stat = { :ip => ip, :path => path, :format => format, :runtime => runtime, :created_at => Time.now } RequestStatistic.create(stat) end endend class RequestStatistic include MongoMapper::Document key :format, String, :index => true, :required => true key :ip, String, :index => true, :required => true key :path, String, :index => true, :required => true key :runtime, Integer, :required => true key :created_at, Time, :required => trueend