123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- import os
- from flask import Flask, request
- from MoneyRecord import MoneyRecord
- 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
- @app.route('/money/<action>', methods=['POST'])
- def money_action(action):
- data = request.get_json()
- r = MoneyRecord(action=action, data=data, logger=logger).money_record_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'/Users/jasonphd/Desktop/gogs/JasonPhdWork/app/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(host='0.0.0.0',port=5005)
|