为烧瓶记录器设置数据库处理程序

时间:2018-10-09 20:35:03

标签: python python-3.x flask

我正在寻找一个日志数据库处理程序,它将Flask当前输出的所有信息(未处理的异常,werkzeug,sqlachemy)以及我的自定义日志消息保存到控制台。

我无法全部设置。问题:

1)为什么没有记录器记录 about 视图中的模拟算术错误?

2)为什么werkzeug记录器无法正确显示已加载的服务器,并且对于模拟的Aritmetic错误,仅输出“请求%s上的错误”。

3)是否有任何简单的方法可以将Flask服务器(及其组件)编写的所有内容通过管道传输到数据库?

感谢您的回答和其他建议。

到目前为止我所做的事情:

models.py

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

core.py

class Log(DB.Model):
    __tablename__ = 'logs'
    id = DB.Column(DB.Integer, primary_key=True) # auto incrementing
    logger = DB.Column(DB.String(100)) # the name of the logger. (e.g. myapp.views)
    level = DB.Column(DB.String(100)) # info, debug, or error?
    trace = DB.Column(DB.String(4096)) # the full traceback printout
    msg = DB.Column(DB.String(4096)) # any custom log you may have included
    created_at = DB.Column(DB.DateTime, default=DB.func.now()) # the current timestamp

    def __init__(self, logger=None, level=None, trace=None, msg=None):
        self.logger = logger
        self.level = level
        self.trace = trace
        self.msg = msg

    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])

run.py

"""
This module contains the core objects of the application:
the Flask (APP) object and the database object.
"""
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from samo.config import CONFIG_BY_NAME, ENVIRONMENT


APP = Flask(__name__)
APP.config.from_object('samo.config')
APP.config.from_object(CONFIG_BY_NAME[ENVIRONMENT])

DB = SQLAlchemy(APP)
DB.create_all()

LOGIN_MANAGER = LoginManager()
LOGIN_MANAGER.init_app(APP)
LOGIN_MANAGER.session_protection = "strong"
LOGIN_MANAGER.login_view = "auth.login"

views.py

from samo.core import APP as app, DB
from flask_wtf.csrf import CSRFProtect
from samo.config import config
from samo.models import Log
import traceback
import logging

class SQLAlchemyHandler(logging.Handler):

    def emit(self, record):
        trace = None
        exc = record.__dict__['exc_info']
        if exc:
            trace = traceback.format_exc(exc)
        log = Log(
            logger=record.__dict__['name'],
            level=record.__dict__['levelname'],
            trace=trace,
            msg=record.__dict__['msg'],)
        DB.session.add(log)
        DB.session.commit()

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

ch = SQLAlchemyHandler()
ch.setLevel(logging.INFO)

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)



loggers = [logger, logging.getLogger('werkzeug'),  logging.getLogger('sqlalchemy'), logging.getLogger('flask.app')]

for l in loggers:
    l.addHandler(ch)

csrf = CSRFProtect()

if __name__ == '__main__':

    csrf.init_app(app)
    logger.critical('TEST CRITICAL ERROR')
    app.run(host=config['ENV']['HOST'])

在数据库中插入了什么

enter image description here

1 个答案:

答案 0 :(得分:0)

万一有人偶然发现

run.py 中,这是我为获得所需结果所做的唯一更改。

from samo.core import APP as app, DB
from flask_wtf.csrf import CSRFProtect
from samo.config import config
from samo.models import Log
import traceback
import logging

class SQLAlchemyHandler(logging.Handler):

    def emit(self, record):
        trace = None
        exc = record.__dict__['exc_info']
        if exc:
            trace = traceback.format_exc() ##CHANGE HERE, removed exc parameter
        log = Log(
            logger=record.__dict__['name'],
            level=record.__dict__['levelname'],
            trace=trace,
            msg=record.__dict__['msg'],)
        DB.session.add(log)
        DB.session.commit()

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

ch = SQLAlchemyHandler()
ch.setLevel(logging.INFO)

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)



loggers = [logger, logging.getLogger('werkzeug'),  logging.getLogger('sqlalchemy'), logging.getLogger('flask.app')]

for l in loggers:
    l.addHandler(ch)

csrf = CSRFProtect()

if __name__ == '__main__':

    csrf.init_app(app)
    logger.critical('TEST CRITICAL ERROR')
    app.run(host=config['ENV']['HOST'])

问题解决了。