import logging import os import traceback from flask import Flask, request from api import * from api import login, search logs_folder = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logs') os.makedirs(logs_folder, exist_ok=True) current_folder = os.path.dirname(os.path.abspath(__file__)) file_handler = logging.FileHandler(filename=f"{current_folder}/logs/app.log", encoding="utf-8") # 配置日志格式 formatter = logging.Formatter("%(asctime)s %(levelname)s[%(funcName)s:%(lineno)s]:%(message)s", "%Y-%m-%d %H:%M:%S") file_handler.setFormatter(formatter) console_handler = logging.StreamHandler() # 配置日志记录器 logger = logging.getLogger() logger.setLevel(logging.INFO) logger.addHandler(file_handler) # 开发的时候打开这行注释,日志会打印在控制台上面 logger.addHandler(console_handler) app = Flask(__name__) app.register_blueprint(login.login_opt, url_prefix="/login") app.register_blueprint(search.search_opt, url_prefix="/search") @app.errorhandler(Exception) def handle_exception(error: Exception): """ 全局异常处理 """ status_code = 500 if isinstance(error, BusinessException): status_code = 200 response = fail_response(error.msg) else: logging.error(error) traceback.print_exc() response = fail_response(str(error)) return response, status_code @app.before_request def log_request(): """ 打印请求 """ logging.info('Request: %s %s', request.method, request.url) logging.info('Request Body: %s', request.get_data(as_text=True)) @app.after_request def log_response(response): """ 打印返回 """ data = response.get_data(as_text=True) if len(data) > 300: logging.info('Response Body: %s', data[:300] + "...") else: logging.info('Response Body: %s', data) return response if __name__ == '__main__': app.run(host="0.0.0.0", port=8978, threaded=True)