2025-12-17 16:40:07 +08:00
|
|
|
|
"""
|
|
|
|
|
|
系统日志视图模块
|
|
|
|
|
|
|
|
|
|
|
|
提供系统日志的 REST API 接口,供前端实时查看系统运行日志。
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
2025-12-17 16:27:58 +08:00
|
|
|
|
import logging
|
|
|
|
|
|
|
|
|
|
|
|
from django.utils.decorators import method_decorator
|
|
|
|
|
|
from django.views.decorators.csrf import csrf_exempt
|
|
|
|
|
|
from rest_framework import status
|
|
|
|
|
|
from rest_framework.permissions import AllowAny
|
|
|
|
|
|
from rest_framework.response import Response
|
|
|
|
|
|
from rest_framework.views import APIView
|
|
|
|
|
|
|
|
|
|
|
|
from apps.common.services.system_log_service import SystemLogService
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@method_decorator(csrf_exempt, name="dispatch")
|
|
|
|
|
|
class SystemLogsView(APIView):
|
2025-12-17 16:40:07 +08:00
|
|
|
|
"""
|
|
|
|
|
|
系统日志 API 视图
|
|
|
|
|
|
|
|
|
|
|
|
GET /api/system/logs/
|
|
|
|
|
|
获取系统日志内容
|
|
|
|
|
|
|
|
|
|
|
|
Query Parameters:
|
|
|
|
|
|
lines (int, optional): 返回的日志行数,默认 200,最大 10000
|
|
|
|
|
|
|
|
|
|
|
|
Response:
|
|
|
|
|
|
{
|
|
|
|
|
|
"content": "日志内容字符串..."
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
Note:
|
|
|
|
|
|
- 当前为开发阶段,暂时允许匿名访问
|
|
|
|
|
|
- 生产环境应添加管理员权限验证
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
# TODO: 生产环境应改为 IsAdminUser 权限
|
2025-12-17 16:27:58 +08:00
|
|
|
|
authentication_classes = []
|
|
|
|
|
|
permission_classes = [AllowAny]
|
|
|
|
|
|
|
|
|
|
|
|
def __init__(self, **kwargs):
|
|
|
|
|
|
super().__init__(**kwargs)
|
|
|
|
|
|
self.service = SystemLogService()
|
|
|
|
|
|
|
|
|
|
|
|
def get(self, request):
|
2025-12-17 16:40:07 +08:00
|
|
|
|
"""
|
|
|
|
|
|
获取系统日志
|
|
|
|
|
|
|
|
|
|
|
|
支持通过 lines 参数控制返回行数,用于前端分页或实时刷新场景。
|
|
|
|
|
|
"""
|
2025-12-17 16:27:58 +08:00
|
|
|
|
try:
|
2025-12-17 16:40:07 +08:00
|
|
|
|
# 解析 lines 参数
|
2025-12-17 16:27:58 +08:00
|
|
|
|
lines_raw = request.query_params.get("lines")
|
|
|
|
|
|
lines = int(lines_raw) if lines_raw is not None else None
|
|
|
|
|
|
|
2025-12-17 16:40:07 +08:00
|
|
|
|
# 调用服务获取日志内容
|
2025-12-17 16:27:58 +08:00
|
|
|
|
content = self.service.get_logs_content(lines=lines)
|
|
|
|
|
|
return Response({"content": content})
|
|
|
|
|
|
except ValueError:
|
|
|
|
|
|
return Response({"error": "lines 参数必须是整数"}, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
logger.exception("获取系统日志失败")
|
|
|
|
|
|
return Response({"error": "获取系统日志失败"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
|