Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikejs/278395 to your computer and use it in GitHub Desktop.
Save mikejs/278395 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import logging
import pymongo
import datetime
class MongoHandler(logging.Handler):
"""
A logging handler that will record messages to a (optionally capped)
MongoDB collection.
>>> connection = pymongo.Connection()
>>> collection = connection.db.log
>>> logger = logging.getLogger("mongotest")
>>> logger.addHandler(MongoHandler(drop=True))
>>> logger.error("Hello, world!")
>>> collection.find_one()['message']
u'Hello, world!'
"""
def __init__(self, level=logging.NOTSET, host="localhost", port=27017,
database='db', collection='log', capped=True, size=100000,
drop=False):
logging.Handler.__init__(self, level)
self.connection = pymongo.Connection(host, port)
self.database = self.connection[database]
if collection in self.database.collection_names():
if drop:
self.database.drop_collection(collection)
self.collection = self.database.create_collection(
collection, {'capped': capped, 'size': size})
else:
self.collection = self.database[collection]
else:
self.collection = self.database.create_collection(
collection, {'capped': capped, 'size': size})
def emit(self, record):
self.collection.save({'when': datetime.datetime.now(),
'levelno': record.levelno,
'levelname': record.levelname,
'message': record.msg})
if __name__ == '__main__':
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment