使用logging模块,记录日志信息
- 安装模块
pip3 install logging
- 脚本示例
vim flask_api_logging.py
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import json
import logging
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route("/flask_api/", methods=['POST', 'GET'])
def flask_api():
data = json.loads(request.get_data(as_text=True))
# 打印debug级别日志
app.logger.debug("data: %s" % (data))
user_id = data.get("id")
user_name = data.get("name")
# 打印info级别日志
app.logger.info("reply: %s" % (data))
return jsonify({"user_id":user_id,"user_name":user_name})
if __name__ == '__main__':
# 添加日志模块,将日志写入到指定文件中,打印DEBUG级别以下日志
app.debug = True
handler = logging.FileHandler('logs/flask.log', encoding='UTF-8')
handler.setLevel(logging.DEBUG)
logging_format = logging.Formatter("%(asctime)s flask %(levelname)s %(message)s")
handler.setFormatter(logging_format)
app.logger.addHandler(handler)
# 启动flask服务
app.run('0.0.0.0', 5000)