Flask设置logger日志模板

logger日志模板

"""flask设置logger日志统一目录: Myapp/utils/logger.py"""
import logging
from logging.handlers import RotatingFileHandler


class Logger(object):

    @staticmethod
    def get_logger(name):
        # 这个name就是下面 fmt_str 日志格式中name显示的名称
        return logging.getLogger(name)

    @staticmethod
    def init_logger(log_path, log_level=logging.INFO):
        """初始化日志模块,并设置日志保存路径"""
        logger = logging.getLogger('')
        fmt_str = '[%(asctime)s][%(name)s][line:%(lineno)d]' \
                  '[%(levelname)s] %(message)s'

        file_handler = RotatingFileHandler(filename=log_path,
                                           maxBytes=1024 * 1024 * 10,
                                           backupCount=10,
                                           encoding='utf-8')
        formatter = logging.Formatter(fmt_str)
        file_handler.setFormatter(formatter)
        logger.addHandler(file_handler)
        logger.setLevel(log_level)


"""flask_manager.py"""
from flask import Flask
from Myapp.utils.logger import Logger

app = Flask(__name__)

if __name__ == '__main__':
    # 初始化日志
    Logger.init_logger("/tmp/logs/flask_logs.log")
    # 在需要使用的地方(不限于启动文件),实例化logger即可
    flask_logger = Logger.get_logger("flask_service")
    flask_logger.info("flask start!")
    app.run()

"""Myapp/views/test.py"""
import json
from flask import request, views, jsonify, make_response
from Myapp.utils.logger import Logger


class Test(views.MethodView):
    methods = ["POST"]

    def post(self):
        data = json.loads(request.data)
        id = data.get("id", None)

        logger = Logger.get_logger(str(id))
        logger.info("正在处理!")

        response = {"result": "success"}
        resp = make_response(jsonify(response))
        return resp

 

posted @ 2022-09-18 21:54  我用python写Bug  阅读(352)  评论(0编辑  收藏  举报