Created
January 15, 2010 20:55
-
-
Save mikejs/278395 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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