使用自定义处理程序的SQLAlchemy日志记录冻结

时间:2018-12-16 23:04:33

标签: python logging sqlalchemy handler

我正在尝试编写自己的Python日志记录处理程序,该处理程序将使用SQLAlchemy将日志记录写入数据库中,而SQLAlchemy还将利用其自身的日志记录机制将其记录到终端中(使用echo = True)。

这是当前的简单+示例代码:

Base = declarative_base()
engine = create_engine('sqlite:///logdb.db', echo=True)
Session = sessionmaker(bind=engine)
class Log(Base):
    __tablename__ = 'Log'
    id = Column(Integer, primary_key=True)
    Log_message = Column(String)
    Timestamp = Column(String)

    def __init__(self, log_message=None, timestamp=None):
        self.Log_message = log_message
        self.Timestamp = timestamp

class DBHandler(logging.Handler):
    def __init__(self):
        logging.Handler.__init__(self)
        format = logging.Formatter('%(asctime)s - %(message)s')
        self.setFormatter(format)

    def emit(self, record):
        self.format(record)
        log = Log(
                log_message=record.__dict__['message'],
                timestamp=record.__dict__['asctime']
                )
        session = Session()
        session.add(log)
        session.commit()

def main():
    dbhandler = DBHandler()

    logging.getLogger().addHandler(dbhandler)
    logging.getLogger().setLevel(logging.DEBUG)
    logging.info('test_message')

但是,我进入终端的唯一日志消息如下:

2018-12-16 23:58:11,994 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS VARCHAR(60)) AS anon_1

并且脚本卡在session.commit()行上。

有可能解决这个问题吗?

0 个答案:

没有答案