Skip to content

Instantly share code, notes, and snippets.

@igrabes
Created March 27, 2014 01:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save igrabes/9798301 to your computer and use it in GitHub Desktop.
Save igrabes/9798301 to your computer and use it in GitHub Desktop.
Request Logger - Write request info to mongo via a sinatra app
require 'sinatra'
require 'mongo'
require 'json'
class RequestLogger
include Mongo
attr_accessor :ip, :path, :method, :body, :url_params
def self.log(request)
log = self.new(request)
log.store
end
def initialize(request)
@ip = request.ip
@path = request.path
@method = request.request_method
@url_params = request.query_string
@body = request.body
end
def store
@mongo_collection = self.class.setup_db_and_collection
json_obj = {:ip => self.ip, :path => self.path, :method => self.method, :url_params => self.url_params}
@mongo_collection.insert(json_obj)
end
def self.setup_db_and_collection
@mongo_client ||= MongoClient.new("localhost", 27017).db('requestLogger')
@mongo_collection = @mongo_client.collection('requests')
end
end
get '/1' do
RequestLogger.log(request)
"Hello World! - page 1"
end
get '/2' do
RequestLogger.log(request)
"Hello World! - page 2"
end
get '/3' do
RequestLogger.log(request)
"Hello World! - page 3"
end
get '/report' do
@mongo_collection = RequestLogger.setup_db_and_collection
view = "<table>
<thead>
<th>IP</th>
<th>Url</th>
<th>Method</th>
<th>Url Params</th>
</thead>
<tbody>
<% @mongo_collection.find.each do |log| %>
<tr>
<td><%= log['ip'] %></td>
<td><%= log['path'] %></td>
<td><%= log['method'] %></td>
<td><%= log['url_params'] %></td>
</tr>
<% end %>
</tbody>
</table>"
erb view
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment