app.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from flask import Flask,request
  2. from user import User
  3. import logging
  4. from logging.handlers import TimedRotatingFileHandler
  5. from datetime import datetime
  6. app = Flask(__name__)
  7. @app.route('/')
  8. def hello_world(): # put application's code here
  9. return 'it works!'
  10. @app.route('/user/<action>', methods=['POST'])
  11. def user_action(action):
  12. data = request.get_json()
  13. r = User(action=action, data=data,logger=logger).user_router()
  14. return r
  15. class CustomLogger:
  16. def __init__(self, log_file):
  17. self.log_file = log_file
  18. self.logger = self._create_logger()
  19. def _create_logger(self):
  20. logger = logging.getLogger(__name__)
  21. logger.setLevel(logging.INFO)
  22. # 创建 TimedRotatingFileHandler 对象
  23. handler = TimedRotatingFileHandler(self.log_file, when='midnight', backupCount=7)
  24. handler.setLevel(logging.INFO)
  25. # 设置日志格式
  26. formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s', datefmt='%Y-%m-%d')
  27. handler.setFormatter(formatter)
  28. logger.addHandler(handler)
  29. return logger
  30. def log(self, message):
  31. self.logger.info(message)
  32. # 使用自定义的 logging 工具类
  33. # 获取当前日期
  34. current_date = datetime.now()
  35. # 获取年月日
  36. year = current_date.year
  37. month = current_date.month
  38. day = current_date.day
  39. # 将年月日格式化为字符串
  40. formatted_date = current_date.strftime("%Y-%m-%d")
  41. logger = CustomLogger(f'logs/{formatted_date}.log')
  42. # 自定义中间件
  43. @app.before_request
  44. def log_request_info():
  45. logger.log(f"url:{request.url} params:{request.get_json()} method:{request.method} ip:{request.remote_addr}")
  46. if __name__ == '__main__':
  47. app.run()