Skip to content

Instantly share code, notes, and snippets.

@carlozamagni
Last active August 29, 2015 13:56
Show Gist options
  • Save carlozamagni/9088446 to your computer and use it in GitHub Desktop.
Save carlozamagni/9088446 to your computer and use it in GitHub Desktop.
Handler for logging module; can be used to redirect logs to a mongodb collection (see configuration example in code comments).
import logging
import datetime
from pymongo import MongoClient
__author__ = 'cazamagni'
'''
Configuration example:
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
mongo_handler = MongoDbHandler(db_url='mongodb://localhost:27017',
db_name='my_app_db',
collection_name='loggedErrors')
mongo_handler.setLevel(logging.INFO)
logger.addHandler(mongo_handler)
'''
class MongoDbHandler(logging.Handler):
def __init__(self, db_url, db_name, collection_name):
logging.Handler.__init__(self)
db = MongoClient(db_url, w=0)
self.logs = db[db_name][collection_name]
def emit(self, record):
timestamp = datetime.datetime.utcnow()
log_entry = {'message': record.message,
'level_name': record.levelname,
'file_name': record.filename,
'module': record.module,
'line_number': record.lineno,
'timestamp': timestamp} # to support time queries and TTL indexes on mongodb
if record.exc_text:
log_entry['stacktrace'] = record.exc_text
self.logs.insert(log_entry)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment