import os from flask import Flask, request from MoneyRecord import MoneyRecord from task import TikTask from user import User import logging from logging.handlers import TimedRotatingFileHandler from datetime import datetime import time app = Flask(__name__) @app.route('/') def hello_world(): # put application's code here return 'it works!' @app.route('/user/', methods=['POST']) def user_action(action): data = request.get_json() r = User(action=action, data=data, logger=logger).user_router() return r @app.route('/money/', methods=['POST']) def money_action(action): data = request.get_json() r = MoneyRecord(action=action, data=data, logger=logger).money_record_router() return r @app.route('/task/', methods=['POST']) def tik_task_action(action): data = request.get_json() r = TikTask(action=action, data=data, logger=logger).tik_task_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'{os.path.dirname(__file__)}/logs/{formatted_date}.log') # logger = CustomLogger(f'/Users/jasonphd/Desktop/gogs/JasonPhdWork/server/flaskProject/logs{formatted_date}.log') # logger = CustomLogger(f'/root/api_server/JasonPhdWork/app/logs/{formatted_date}.log') # 自定义中间件 @app.before_request def log_request_info(): data = request.get_json() data["intime"] = int(time.time()) logger.log(f"url:{request.url} params:{data} method:{request.method} ip:{request.remote_addr}") if __name__ == '__main__': app.run(host='0.0.0.0', port=5005)