优化更新
This commit is contained in:
@@ -135,8 +135,11 @@ def register_operation_log(app):
|
||||
1. 请求方法为 POST/PUT/DELETE/PATCH
|
||||
2. 路径不在排除列表中
|
||||
3. HTTP 状态码为 2xx
|
||||
4. 业务 code 为 0(成功)
|
||||
5. 非内部调用
|
||||
4. 非内部调用
|
||||
|
||||
记录范围:
|
||||
- 成功操作(code=0):status=0(正常)
|
||||
- 失败操作(code!=0,如演示环境拦截):status=1(异常),记录错误信息
|
||||
"""
|
||||
# 只记录写操作
|
||||
if request.method not in ("POST", "PUT", "DELETE", "PATCH"):
|
||||
@@ -147,24 +150,28 @@ def register_operation_log(app):
|
||||
if _is_excluded_path(path):
|
||||
return response
|
||||
|
||||
# 只记录成功操作(HTTP 2xx 且业务 code=0)
|
||||
# HTTP 非 2xx 不记录(如 404、500 等)
|
||||
if not (200 <= response.status_code < 300):
|
||||
return response
|
||||
|
||||
try:
|
||||
data = response.get_json(silent=True)
|
||||
if data and data.get("code", 0) != 0:
|
||||
return response
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 内部调用不记录
|
||||
if getattr(g, "_internal_call", False):
|
||||
return response
|
||||
|
||||
# 异步记录,不阻塞响应
|
||||
# 判断业务状态:code=0 为成功,其他为失败
|
||||
status = 0 # 默认成功
|
||||
error_msg = ""
|
||||
try:
|
||||
_write_log(response)
|
||||
data = response.get_json(silent=True)
|
||||
if data and data.get("code", 0) != 0:
|
||||
status = 1 # 业务失败
|
||||
error_msg = data.get("msg", "操作失败")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 记录日志(成功和失败都记录)
|
||||
try:
|
||||
_write_log(response, status=status, error_msg=error_msg)
|
||||
except Exception as e:
|
||||
logger.warning(f"记录操作日志失败: {str(e)}")
|
||||
|
||||
@@ -173,7 +180,7 @@ def register_operation_log(app):
|
||||
logger.info("操作日志中间件注册成功")
|
||||
|
||||
|
||||
def _write_log(response):
|
||||
def _write_log(response, status=0, error_msg=""):
|
||||
"""
|
||||
写入操作日志
|
||||
|
||||
@@ -181,6 +188,8 @@ def _write_log(response):
|
||||
|
||||
Args:
|
||||
response: Flask 响应对象
|
||||
status: 操作状态(0-正常,1-异常)
|
||||
error_msg: 错误信息(失败时)
|
||||
"""
|
||||
from src.core.security import get_username
|
||||
from src.common.utils.ip import get_client_ip
|
||||
@@ -217,7 +226,7 @@ def _write_log(response):
|
||||
title=title,
|
||||
log_type=log_type,
|
||||
source=0, # OperationLog.Source.ADMIN
|
||||
status=0, # OperationLog.Status.NORMAL
|
||||
status=status,
|
||||
method=request.endpoint or "",
|
||||
request_method=request.method,
|
||||
url=request.path,
|
||||
@@ -228,7 +237,7 @@ def _write_log(response):
|
||||
os=ua_info.get("os", "未知"),
|
||||
browser=ua_info.get("browser", "未知"),
|
||||
consume_time=consume_time,
|
||||
error="",
|
||||
error=error_msg,
|
||||
username=username,
|
||||
)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user