折腾:
【已解决】CentOS服务器中搭建Python的Flask的REST API
期间,给Flask中添加log,且能输出到文件中。
参考:
直接去试试:
<code>app = Flask(__name__) log = app.logger log.debug("app=%s", app) api = Api(app) log.info("api=%s", api) </code>
结果调试时没有打印出log:
flask log
Logging — Flask Documentation (0.13-dev)
Application Errors — Flask Documentation (0.12)
flask app logger not work
python – Flask logging not working at all – Stack Overflow
好像是:
默认的logger是warning之上的才打印,所以此处info和debug没有输出?
果然是的:
此处Flask的app.logger,默认的level是WARNING
-》只有warning以上的才会输出
-〉所以此处的,warning以上的error能输出,而warning和info,没有输出
-》所以为了能让debug输出的话,则去设置level即可:
<code>import logging # from flask_pymongo import PyMongo app = Flask(__name__) app.logger.setLevel(logging.INFO) log = app.logger log.error("app=%s", app) log.warning("app=%s", app) log.debug("app=%s", app) </code>
结果warning和info还是没有输出
然后再去解决:
【已解决】Flask的log输出异常:file和console中无法输出指定的level的log
然后接着去:
【总结】
此处通过:
<code>from flask import Flask from flask import jsonify from flask_restful import Resource, Api, reqparse import logging from logging.handlers import RotatingFileHandler # from flask_pymongo import PyMongo app = Flask(__name__) FLASK_APP = "RobotQA" LOG_FILE_FILENAME = "logs/" + FLASK_APP + ".log" LOG_FORMAT = "[%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s] %(message)s" app.config['LOG_FILE_FILENAME'] = LOG_FILE_FILENAME app.config["LOG_FORMAT"] = LOG_FORMAT logFormatterStr = app.config["LOG_FORMAT"] logFormatter = logging.Formatter(logFormatterStr) fileHandler = RotatingFileHandler( app.config['LOG_FILE_FILENAME'], maxBytes=2*1024*1024, backupCount=3, encoding="UTF-8") fileHandler.setLevel(logging.DEBUG) fileHandler.setFormatter(logFormatter) app.logger.addHandler(fileHandler) streamHandler = logging.StreamHandler() streamHandler.setFormatter(logFormatter) streamHandler.setLevel(logging.INFO) app.logger.addHandler(streamHandler) app.logger.setLevel(logging.DEBUG) # set root log level log = app.logger log.error("error: app=%s", app) log.warning("warning: app=%s", app) log.info("info: app=%s", app) log.debug("debug: app=%s", app) api = Api(app) log.info("api=%s", api) ... if __name__ == "__main__": # app.debug = True app.run() </code>
实现了log输出:
转载请注明:在路上 » 【已解决】Flask中添加log且输出到文件中