flask项目中使用logging记录服务日志

文章目录

  • 前言
    • 目录结构
      • manager.py 项目主入口
      • app init.py
      • setting.py flask配置文件
      • view.py 视图函数文件

前言

记录日志,在任何项目中,都是很重要的。在Flask项目中,即有Flask提供的logger可以用来记录log,也可以通过直接使用Python的logging模块自定义logger来记录。其中,日志信息包含了几个等级,如下,本次测试项目中使用了两个等级的日志信息

级别 说明
DEBUG 调试模式,打印最详细的日志信息
INFO 按照预期工作的日志
WARNING 服务警告日志信息
ERROR 服务错误日志信息
CRITICAL 严重错误,程序 已不能继续运行

目录结构

manager.py
app
    │setting.py
    │__init__.py
    │
    ├─cms
    │      aa.py
    │      __init__.py
    │
    ├─logs
          error.log
          info.log
 

manager.py 项目主入口

from app import created_app

app = created_app()

if __name__ == '__main__':
    app.logger.info("开始你的BUG之旅")
    app.run(host="0.0.0.0")

app init.py

from flask import Flask
from .setting import config


def created_app():
    app = Flask(__name__)
    # 导入配置
    app.config.from_object(config["development"])
    config["development"].init_app(app)
    # 导入路由
    from app.cms import bp
    app.register_blueprint(bp)
    return app

setting.py flask配置文件

import logging
import os

# 项目根目录
basedir = os.path.abspath(os.path.dirname(__file__))


class InfoFilter(logging.Filter):
    def filter(self, record):
        """only use INFO
        筛选, 只需要 INFO 级别的log
        :param record:
        :return:
        """
        if logging.INFO <= record.levelno < logging.ERROR:
            # 已经是INFO级别了
            # 然后利用父类, 返回 1
            return super().filter(record)
        else:
            return 0


class Config(object):
    DEBUG = False
    TESTING = False
    DB_SERVER = "localhost"
    DB_PORT = 3306
    DB_USER = "root"
    DB_PWD = "123456"
    DB_BASE = ""
    DATABASE_URI = {"host": DB_SERVER, "user": DB_USER, "pwd": DB_PWD, "database": DB_BASE,
                    "port": DB_PORT}
    # 日志配置信息
    LOG_PATH = os.path.join(basedir, 'logs')
    LOG_PATH_ERROR = os.path.join(LOG_PATH, 'error.log')
    LOG_PATH_INFO = os.path.join(LOG_PATH, 'info.log')
    LOG_FILE_MAX_BYTES = 100 * 1024 * 1024
    # 轮转数量是 10 个
    LOG_FILE_BACKUP_COUNT = 10

    @staticmethod
    def init_app(app):
        pass


class DevelopmentAPIConfig(Config):
    DEBUG = True
    DB_SERVER = "localhost"
    DB_PORT = 3306
    DB_USER = "username"
    DB_PWD = "password"
    DB_BASE = ""
    DATABASE_URI = {"host": DB_SERVER, "user": DB_USER, "pwd": DB_PWD, "database": DB_BASE,
                    "port": DB_PORT}

    @classmethod
    def init_app(cls, app):
        Config.init_app(app)

        # email errors to the administrators
        import logging
        from logging.handlers import RotatingFileHandler
        # Formatter
        formatter = logging.Formatter(
            '%(asctime)s %(levelname)s %(process)d %(thread)d '
            '%(pathname)s %(lineno)s %(message)s')

        # FileHandler Info
        file_handler_info = RotatingFileHandler(filename=cls.LOG_PATH_INFO)
        file_handler_info.setFormatter(formatter)
        file_handler_info.setLevel(logging.INFO)
        info_filter = InfoFilter()
        file_handler_info.addFilter(info_filter)
        app.logger.addHandler(file_handler_info)

        # FileHandler Error
        file_handler_error = RotatingFileHandler(filename=cls.LOG_PATH_ERROR)
        file_handler_error.setFormatter(formatter)
        file_handler_error.setLevel(logging.ERROR)
        app.logger.addHandler(file_handler_error)

view.py 视图函数文件

from app.cms import bp
from flask import current_app as app, jsonify

from app.until.DBTools import DataBaseSession
from app.until.decmail_bill import decimal_err


@bp.route("/info/", methods=["GET"])
def index():
    db_config = app.config["DATABASE_URI"]
    session = DataBaseSession(db_config)
    sql = """SELECT * FROM `order`.`sp_order` WHERE `order_id` = '1916' LIMIT 0, 1000"""
    app.logger.info(sql)
    # app.logger.warning(sql)
    res = session.query_dict_fetchall(sql)
    if res:
        return jsonify(decimal_err(res))
    return "订单号不存在"

你可能感兴趣的:(笔记)