# Adapted from https://github.com/le0pard/mongodb_logger/ require 'mongo_request_logger/adapters/base' module MongoRequestLogger module Adapters class Mongo < Base def initialize(options = {}) @authenticated = false @configuration = options.with_indifferent_access @configuration['host'] ||= '127.0.0.1' @configuration['port'] ||= '27017' @configuration['collection'] ||= 'server_log' connect check_for_collection end def connect if @configuration['url'] uri = URI.parse(@configuration['url']) @configuration['database'] = uri.path.gsub(/^\//, '') @connection ||= mongo_connection_object.db(@configuration['database']) @authenticated = true else @connection ||= mongo_connection_object.db(@configuration['database']) if @configuration['username'] && @configuration['password'] # the driver stores credentials in case reconnection is required @authenticated = @connection.authenticate(@configuration['username'], @configuration['password']) end end end def reconnect connect end def create_collection @connection.create_collection(collection_name, {:capped => true, :size => @configuration['capsize'].to_i*1024*1024}) end def create_index field @collection.create_index(field) end def insert_log_record(record) # TODO: we should make this non-safe? @collection.insert(record) end def collection_stats collection_stats_hash(@collection.stats) end def query(criteria, options={}) q = @collection.find(criteria).sort('timestamp', -1) if options[:limit] q = q.limit(options[:limit]) end q end def find_by_id(id) @collection.find_one(::BSON::ObjectId(id)) end def clear! raise NotImplementedError end private def mongo_connection_object if @configuration['hosts'] conn = ::Mongo::ReplSetConnection.new(*(@configuration['hosts'] << {:connect => true, :pool_timeout => 6})) @configuration['replica_set'] = true elsif @configuration['url'] conn = ::Mongo::Connection.from_uri(@configuration['url']) else conn = ::Mongo::Connection.new(@configuration['host'], @configuration['port'], :connect => true, :pool_timeout => 6) end @connection_type = conn.class conn end end end end