Explorar o código

日志记入文件 。

tanlie hai 1 mes
pai
achega
752faba0f6
Modificáronse 2 ficheiros con 32 adicións e 9 borrados
  1. 25 2
      FastApi/app/__init__.py
  2. 7 7
      FastApi/app/mobile/views/user_views.py

+ 25 - 2
FastApi/app/__init__.py

@@ -4,6 +4,8 @@ auther: tanlie
 date: 2026/8/30
 """
 import logging
+import os
+from logging.handlers import RotatingFileHandler
 import traceback
 from fastapi import FastAPI, Request, HTTPException
 from fastapi.exceptions import RequestValidationError
@@ -12,9 +14,30 @@ from fastapi.responses import JSONResponse
 from app.mobile import register_mobile_routes
 from app.core.response import error_response
 
-# Basic logging configuration for the app; applications may override this
-logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
+# Configure logging: write to logs/app.log (rotating) and also to console. Avoid duplicate handlers.
 logger = logging.getLogger("app")
+if not logger.handlers:
+    # Determine logs directory relative to this file (project-root/app/../logs)
+    base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
+    log_dir = os.path.join(base_dir, "logs")
+    os.makedirs(log_dir, exist_ok=True)
+    log_file = os.path.join(log_dir, "app.log")
+
+    formatter = logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s")
+
+    # Rotating file handler
+    file_handler = RotatingFileHandler(log_file, maxBytes=10 * 1024 * 1024, backupCount=7, encoding="utf-8")
+    file_handler.setFormatter(formatter)
+    file_handler.setLevel(logging.INFO)
+    logger.addHandler(file_handler)
+
+    # Console handler
+    console_handler = logging.StreamHandler()
+    console_handler.setFormatter(formatter)
+    console_handler.setLevel(logging.INFO)
+    logger.addHandler(console_handler)
+
+    logger.setLevel(logging.INFO)
 
 
 def create_app():

+ 7 - 7
FastApi/app/mobile/views/user_views.py

@@ -3,37 +3,37 @@ user - mobile user views
 auther: tanlie
 date: 2026/8/30
 """
-from typing import Any
+import logging
 
 from fastapi import APIRouter, Body, Query
 
+from app.core.response import success_response
 from app.mobile.req.user import UserLoginReq
 
 user = APIRouter(prefix="/dgapi/mobile/user", tags=["mobile user"])
 
-
-from app.core.response import success_response, error_response
+logger = logging.getLogger("app")
 
 
 @user.get("/login/captcha", summary="获取验证码")
 def get_captcha(type: int = Query(default=1, description="验证码类型,1:登录验证码,2:注册验证码")):
-    print(f"获取验证码,type={type}")
+    logger.info("获取验证码,type=%s", type)
     return success_response(data={"type": type}, msg="获取验证码成功")
 
 
 @user.post("/login", summary="登录")
 def login(req: UserLoginReq):
-    print(f"用户登录,请求参数:{req}")
+    logger.info("用户登录,请求参数:%s", req)
     return success_response(data={"user": req.model_dump()}, msg="登录成功")
 
 
 @user.post("/logout", summary="登出")
 def logout(userId: int = Body(description="用户ID")):
-    print(f"用户登出,userId={userId}")
+    logger.info("用户登出,userId=%s", userId)
     return success_response(data={"userId": userId}, msg="退出成功")
 
 
 @user.get("/wish-summary", summary="心愿单摘要")
 def wish_summary():
-    print("获取心愿单摘要")
+    logger.info("获取心愿单摘要")
     return success_response(data={"wish_summary": "心愿单"}, msg="查询成功")