Skip to content

Instantly share code, notes, and snippets.

@max-power
Last active August 29, 2015 13:56
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 max-power/9135174 to your computer and use it in GitHub Desktop.
Save max-power/9135174 to your computer and use it in GitHub Desktop.
Gem::Specification.new do |s|
s.name = 'cptn-log'
s.version = '0.0.2'
s.platform = Gem::Platform::RUBY
s.author = 'Kevin Melchert'
s.email = 'kevin.melchert@gmail.com'
s.summary = 'MongoDB Logger.'
s.description = 'MongoDB Logger.'
s.files = ['cptn-log.rb']
s.require_path = '.'
end
module Captain
class Logbook
def initialize(database, name: 'cptn.log', size: 5242880, max: nil)
@db, @name, @size, @max = database, name, size, max
end
%i(debug info warn error fatal).each do |level|
define_method(level) { |msg, extra={}| log(level, msg, extra) }
end
def head(n=20)
find(n, Mongo::Index::ASCENDING)
end
def tail(n=20)
find(n, Mongo::Index::DESCENDING)
end
def clear
collection.drop
end
private
def log(level, message, extra = {})
collection.insert_one({ l: level.to_s, m: message.to_s, x: extra })
end
def find(n, order)
collection.find.sort({"$natural" => order}).limit(n)
end
def collection
@db.collection collection_name, capped: true, size: @size, max: @max
end
def collection_name
@name.respond_to?(:call) ? @name.call : @name
end
end
end
client = Mongo::Client.new(['127.0.0.1:27017'])
logger = Captain::Logbook.new(client['test'], name: -> { "cptn.log.#{Time.now.utc.strftime('%Y.%m.%d.%H')}" })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment