|
@@ -0,0 +1,67 @@
|
|
|
|
+from flask import Flask,request
|
|
|
|
+from user import User
|
|
|
|
+import logging
|
|
|
|
+from logging.handlers import TimedRotatingFileHandler
|
|
|
|
+from datetime import datetime
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+app = Flask(__name__)
|
|
|
|
+
|
|
|
|
+@app.route('/')
|
|
|
|
+def hello_world(): # put application's code here
|
|
|
|
+ return 'it works!'
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+@app.route('/user/<action>', methods=['POST'])
|
|
|
|
+def user_action(action):
|
|
|
|
+ data = request.get_json()
|
|
|
|
+ r = User(action=action, data=data,logger=logger).user_router()
|
|
|
|
+ return r
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+class CustomLogger:
|
|
|
|
+ def __init__(self, log_file):
|
|
|
|
+ self.log_file = log_file
|
|
|
|
+ self.logger = self._create_logger()
|
|
|
|
+
|
|
|
|
+ def _create_logger(self):
|
|
|
|
+ logger = logging.getLogger(__name__)
|
|
|
|
+ logger.setLevel(logging.INFO)
|
|
|
|
+
|
|
|
|
+ # 创建 TimedRotatingFileHandler 对象
|
|
|
|
+ handler = TimedRotatingFileHandler(self.log_file, when='midnight', backupCount=7)
|
|
|
|
+ handler.setLevel(logging.INFO)
|
|
|
|
+
|
|
|
|
+ # 设置日志格式
|
|
|
|
+ formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s', datefmt='%Y-%m-%d')
|
|
|
|
+ handler.setFormatter(formatter)
|
|
|
|
+
|
|
|
|
+ logger.addHandler(handler)
|
|
|
|
+ return logger
|
|
|
|
+
|
|
|
|
+ def log(self, message):
|
|
|
|
+ self.logger.info(message)
|
|
|
|
+
|
|
|
|
+# 使用自定义的 logging 工具类
|
|
|
|
+# 获取当前日期
|
|
|
|
+current_date = datetime.now()
|
|
|
|
+
|
|
|
|
+# 获取年月日
|
|
|
|
+year = current_date.year
|
|
|
|
+month = current_date.month
|
|
|
|
+day = current_date.day
|
|
|
|
+
|
|
|
|
+# 将年月日格式化为字符串
|
|
|
|
+formatted_date = current_date.strftime("%Y-%m-%d")
|
|
|
|
+logger = CustomLogger(f'logs/{formatted_date}.log')
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+# 自定义中间件
|
|
|
|
+@app.before_request
|
|
|
|
+def log_request_info():
|
|
|
|
+ logger.log(f"url:{request.url} params:{request.get_json()} method:{request.method} ip:{request.remote_addr}")
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+if __name__ == '__main__':
|
|
|
|
+ app.run()
|