Skip to content

Instantly share code, notes, and snippets.

@josuebrunel
Last active August 29, 2015 14:11
Show Gist options
  • Save josuebrunel/6fe1492537c8b3c141aa to your computer and use it in GitHub Desktop.
Save josuebrunel/6fe1492537c8b3c141aa to your computer and use it in GitHub Desktop.
Python : Logging into Database
import logging
import traceback
import logging.handlers
from logging import Handler, Logger
import sqlalchemy
from sqlalchemy.sql import func
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, DateTime
from sqlalchemy import create_engine
BaseModel = declarative_base()
engine = create_engine('mysql://user:password@localhost/dblogger')
BaseModel.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
class LogModel(BaseModel):
__tablename__ = 'dblogs'
id = Column(Integer, primary_key=True)
logger = Column(String(25))
level = Column(String(25))
trace = Column(String(64))
message = Column(String(128))
created_at = Column(DateTime, default=func.now())
def __init__(self, logger=None, level=None, trace=None, message=None):
self.logger = logger
self.level = level
self.trace = trace
self.message = message
def __unicode__(self,):
return self.__repr__()
def __repr__(self,):
return "<Log: %s - %s>" % (self.created_at.strftime('%m/%d/%Y-%H:%M:%S'), self.msg[:50])
class SqlAlcghemyHandler(Handler):
def __init__(self, ):
super(SqlAlcghemyHandler, self).__init__()
def emit(self, record):
trace = None
exc = record.__dict__['exc_info']
if exc:
trace = traceback.format_exc(exc)
log = LogModel (
logger = record.__dict__['name'],
level = record.__dict__['levelname'],
trace = trace,
message = record.__dict__['msg'],
#message = self.format(record)
)
session.add(log)
session.commit()
class MyLogger(Logger):
def __init__(self, name):
super(MyLogger, self).__init__(name)
self.setLevel(logging.INFO)
myhandler = SqlAlcghemyHandler()
myhandler.setFormatter(logging.Formatter('[%(name)s %(asctime)s %(levelname)s]: %(message)s'))
self.addHandler(myhandler)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment