Flask自带了logger模块来记录日志,那么我们应用在生产中是需要记录到文件了,为了防止我们生产中所有日志存在一个文件中导致日志文件太大而不方便查找信息,所以我们需要配置下每天生成一个文件独自记录每天的日志情况,主要还是配置应用工厂函数create_app,在原有的基础上添加配置,直接注册到flask中,原有配置请看我之前的笔记https://sulao.cn/post/658.html
那么我们来看看如何配置日志到应用工厂
#!/usr/bin/python3 #coding:utf-8 from flask import Flask from app.web import web from config import load_json from .common import db,mail import logging import os import time import logging config = load_json() def create_app(): app = Flask(__name__) secret_key(app) configure_db(app) db.init_app(app) register_blueprint(app) configure_mail(app) mail.init_app(app) configure_logger(app) return app def secret_key(app): app.secret_key = 'sulao' def configure_db(app): #查询时会显示原始SQL语句 app.config['SQLALCHEMY_ECHO'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://{db_user}:{db_pass}@{db_host}:{db_port}/{db_name}?charset=utf8mb4'.format(db_user=config['db']['db_user'], db_pass=config['db']['db_pass'], db_host=config['db']['db_host'], db_port=config['db']['db_port'], db_name=config['db']['db_name']) def configure_mail(app): app.config['MAIL_SERVER'] = config['mail']['mail_host'] app.config["MAIL_PORT"] = config['mail']['mail_port'] app.config["MAIL_USE_SSL"] = True app.config["MAIL_USERNAME"] = config['mail']['mail_user'] app.config["MAIL_PASSWORD"] = config['mail']['mail_pass'] def configure_logger(app): log_dir_name = "logs" log_file_name = 'logger-' + time.strftime('%Y-%m-%d', time.localtime(time.time())) + '.log' log_file_str = log_dir_name + os.sep + log_file_name log_level = logging.WARNING handler = logging.FileHandler(log_file_str, encoding='UTF-8') handler.setLevel(log_level) logging_format = logging.Formatter( '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s') handler.setFormatter(logging_format) app.logger.addHandler(handler) def register_blueprint(app): app.register_blueprint(web, url_prefix='')
定义一个configure_logger函数,然后再应用工厂中初始化配置,然后我们去需要调用的模块中直接导入create_app应用工厂函数,直接看我sendmail的实例
#!/usr/bin/python3 #coding:utf-8 from flask import Flask,request,jsonify,abort,current_app from app.common import mail,logger from config import load_json from . import web config = load_json() @web.route("/sendmail", methods=['GET', 'POST']) def sendmail(): if request.method == "POST": msg = Message( subject = request.form.get("subject"), sender= config["mail"]["mail_user"], recipients= [request.form.get("sender")]) msg.body = request.form.get("html") try: mail.send(msg) return jsonify({"rtn": 0, "message": "OK"}) except Exception as e: return jsonify({"rtn": 1, "message": e}) else: current_app.logger.warning("非法访问!") abort(403)
我们直接访问http://localhost:5000/sendmail,然后日志写入了今日生成的日志文件