flask添加日志功能

项目目录结构

![在这里插入图片描述](https://img-blog.csdnimg.cn/f388cc1c7b32444fbbd2e38de5553565.png#pic_center)

代码部分

import logging

import flask
from logging import handlers


class Mylogger(object):
    def __init__(self, log_path, log_name):
        # 1.指明日志记录到哪个文件 "F:/xxx/xx" + "info.config"
        logfile = log_path + log_name
        # 2.配置日志操作器
        handler = handlers.RotatingFileHandler(logfile, maxBytes=1024 * 1024, backupCount=5, encoding='utf-8')
        # 3.设置日志格式
        fmt = "%(levelname)s-%(asctime)s-%(module)s-%(lineno)d-%(message)s"
        # 4. 配置格式实例
        formatter = logging.Formatter(fmt)
        # 5.操作器加载格式实例
        handler.setFormatter(formatter)
        # 6.创建logger实例
        self.logger = logging.getLogger()
        # 7.给实例增加日志操作器
        self.logger.addHandler(handler)
        # 8.给实例增加日志输出登记
        self.logger.setLevel(logging.DEBUG)

    def get_logger(self):
        return self.logger


from flask import Flask,request,jsonify

import os
import configparser
app = Flask(__name__)
# 1.获取根目录
root_path = os.path.split(os.path.realpath(__file__))[0]
# 2. 设置日志解析实例
cf = configparser.ConfigParser()
# 3.读取日志文件
res = cf.read(root_path+"/config/log.conf")
#4. 创建自定义日志类的实例对象
logger = Mylogger(root_path + cf.get("log","LOG_PATH"),cf.get("log","LOG_NAME")).get_logger()

@app.route("/index",methods=["POST", "GET"])
def demo():
    try:
        print(1/0)
    except Exception as e:
        logger.error(e)


if __name__ == '__main__':
    app.run(debug=True,port=8080)

你可能感兴趣的:(flask,python,后端)